Reputation:
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 !
Upvotes: 0
Views: 74
Reputation: 19806
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)]
Upvotes: 1
Reputation: 17064
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)]
Upvotes: 1
Reputation:
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)))
Upvotes: 1