0

I had to make a file : planets.txt with information about planets. The file looks like this:

Planet1 100 200

planet2 200 300

planet3 400 250

I have to write a function in python that returns a list with tuples of this information like this :

[(100,200),(200,300),(400,250)]

The problem is that I don't know how to write this function. Is there anyone who can help me? Thank you very very much !

wwii
  • 23,232
  • 7
  • 37
  • 77
  • Are the newlines between the "real" lines in `planets.txt` actually there? –  Dec 03 '16 at 15:34
  • Start reading through [the Tutorial](https://docs.python.org/3/tutorial/index.html) and practicing the examples - it will give you ideas. More resources - https://wiki.python.org/moin/BeginnersGuide/Programmers. Have you read/practiced the instructional material you received? – wwii Dec 03 '16 at 15:36

3 Answers3

1

Something like this perhaps?

ret = []
lines = open('file.txt').readlines()
for line in lines:
    name, first, second = line.split(' ')
    ret.append((int(first), int(second)))
1

You need to split each line of your file and append the tuple of the second and the third items of each resulted list to res list like below:

res = []

with open('planets.txt', 'r') as f:
    for line in f:
        if line.split():  # I add this because from your input, seems that your file contains some blank lines!
            res.append(tuple(line.split()[1:]))

Output:

>>> res
[('100', '200'), ('200', '300'), ('400', '250')]

You can convert each tuple's items to integers like this:

>>> [tuple(map(int, item)) for item in res]
[(100, 200), (200, 300), (400, 250)]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • There's no need to call `.readlines()`. Just loop `for line in f:` and avoid holding all the lines in memory for no reason when you only need one at a time while parsing (Note: I up-voted anyway, because you were the only answer that actually used `with` appropriately) – ShadowRanger Dec 03 '16 at 15:52
  • @ShadowRanger Thanks. I know that `readlines()` is not required. I just like explicit things, but I will remove it anyway! – ettanany Dec 03 '16 at 15:55
1

If you are looking for compact code.

f = open('your_file_path').readlines()
print [tuple(map(int,a.split()[1:])) for a in f if a != '\n']

Output:

[(100, 200), (200, 300), (400, 250)]
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
  • 2
    Why don't use the `with` keyword ? – martijnn2008 Dec 03 '16 at 15:48
  • Good question. Was making it compact. `with` is a better option. I was wondering what will happen to file object since reference count is zero. Check this answer: http://stackoverflow.com/questions/1834556/does-a-file-object-automatically-close-when-its-reference-count-hits-zero – Mohammad Yusuf Dec 03 '16 at 17:15