我有一个包含以下内容的文本文件:
name: Joe
score: 77
class: Jupiter
name: Jess
score: 87
class: Neptune
.
.
.
我正在使用python将文件内容读入两个不同的列表。我想要的格式是:
list1 = [['Joe',77],['Jess',87]]
list2 = [['Joe','Jupiter'],['Jess','Neptune']]
我试着写:
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])
我可以感觉到,我正在以一种相当奇怪的方式阅读文件内容(if“name”)子句。有没有更好的方法呢?
答案 0 :(得分:1)
我会使用dicts寻求解决方案,以便以后更轻松地访问所有数据。在这个例子中,我使用'name'作为键。
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)
输出:
[{'Joe': {'score': 77, 'class': 'Jupiter'}}, {'Jess': {'score': 87, 'class': 'Neptune'}}]
或者修复原始代码,使其按预期工作:
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)
输出:
[['Joe', 77], ['Jess', 87]]
[['Joe', 'Jupiter'], ['Jess', 'Neptune']]