I have a text file containing:
name: Joe
score: 77
class: Jupiter
name: Jess
score: 87
class: Neptune
.
.
.
and I'm using python to read in the file content into two different list. The format i wanted is:
list1 = [['Joe',77],['Jess',87]]
list2 = [['Joe','Jupiter'],['Jess','Neptune']]
and i tried writing:
filename = open("student.txt","r")
studFile = filename
list1 = []
list2 = []
for line in studFile:
value = line.strip().split(": ")
if "name" in line:
list1.append(value[1])
list2.append(value[1])
if "score" in line:
list1.append(int(value[1]))
if "class" in line:
list2.append(value[1])
I can feel as in I'm reading in the file content in a rather strange way with the ( if "name" ) clause. Is there a better way of doing this?
I would go for a solution using dicts, makes it easier to access all the data later on. In this example I use 'name' as key.
list1 = []
tmp_dict = {}
with open('student.txt','r') as file:
for line in file:
value = line.strip().split(': ')
if 'name' in line:
name = value[1]
tmp_dict[name] = {}
if 'score' in line:
tmp_dict[name]['score'] = int(value[1])
if 'class' in line:
tmp_dict[name]['class'] = value[1]
list1.append(tmp_dict)
tmp_dict = {}
print(list1)
Output:
[{'Joe': {'score': 77, 'class': 'Jupiter'}}, {'Jess': {'score': 87, 'class': 'Neptune'}}]
Or to fix your original code to make it work as expected:
list1 = []
list2 = []
name = None
with open('student.txt','r') as file:
for line in file:
value = line.strip().split(': ')
if 'name' in line:
name = value[1]
if 'score' in line:
list1.append([name, int(value[1])])
if 'class' in line:
list2.append([name, value[1]])
print(list1)
print(list2)
Output:
[['Joe', 77], ['Jess', 87]]
[['Joe', 'Jupiter'], ['Jess', 'Neptune']]
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.