I have a file opened, and I'm extracting data from list data. The list data has different names and different numbers for each line in the for
loop. How do I save each name and its corresponding nums in a tuple? ( name
, num1
, num2
).
fp = open(file_name, 'r')
for line in fp:
line.split('\t')
line = line.split()
name = line[0]
num1 = line[2]
name2 = line[3]
You can use a list comprehension to iterate over the file and create a list of tuples:
with open(file_name, 'r') as fp:
my_tuples = [(l[0], l[2], l[3]) for l in (line.split() for line in fp)]
And if you want names, suggest you make some dicts like:
names = "name", "num1", "num2"
my_dicts = [dict(zip(names, line)) for line in my_tuples]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.