将嵌套列表保存到文本文件中

时间:2017-09-25 16:05:34

标签: python

问题1: 我想创建一个程序,从一个人收集名称,年龄和年份组。然后我想将它保存到嵌套循环中。

AD = [["Name","Age","Year"],["Mark","15","11"]]

Inp = input("Name:")
AD.append(Inp)

Inp = input("Age:")
AD.append(Inp)

Inp = input("Year:") 
AD.append(Inp)

print(AD)

所以我试过了......

Name:Jack
Age:14
Year:10
[['Name', 'Age', 'Year'], ['Mark', '15', '11'], 'Jack', '14', '10']
>>> 

我希望结果看起来像......

Name:Jack
Age:14
Year:10
[['Name', 'Age', 'Year'], ['Mark', '15', '11'], ['Jack', '14', '10']]
>>> 

问题2:我希望保存并从文件中读取。

AD = [["Name","Age","Year"],["Mark","15","11"]]

Inp = input("Name:")
AD.append(Inp)

Inp = input("Age:")
AD.append(Inp)

Inp = input("Year:")
AD.append(Inp)

File = open("Details.txt","w")
File.write(AD)
File.close()

print(AD)

然后它出现了" write()"的问题。只使用字符串。如何轻松保存这些信息,这样当我给出一个名字时,我可以用它来找到与之相关的2个数字?

谢谢< 3

2 个答案:

答案 0 :(得分:0)

问题1:

AD = [["Name","Age","Year"],["Mark","15","11"]]

name = input("Name:")
age = input("Age:")
year = input("Year:") 

AD.append([name, age, year])
print(AD)

问题2:

with open('Details.txt','w') as f:
    f.write('\n'.join([','.join(person) for person in AD]))

with open('Details.txt', 'r') as f:
   lines = f.readlines()
   AD = {}
   for line in list(lines)[1:]:
       name, age, year = line.split(',')
       AD[name] = [age, year]

name = input('Wich person do you want to squery? ')
age, year = AD[name]
print('This person has age {0} and year {1}'.format(age, year))

答案 1 :(得分:0)

如果您不介意保存为CSV文件,则可以使用这些列表创建包含3列的Panda数据框,然后另存为CSV文件。稍后您可以阅读CSV文件并获取" Age"的值。和"年"基于" Name"中的值的列柱