简体   繁体   English

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

[英]Saving an nested list into a text file

Problem 1: I want to create a program that gathers the Name, Age and Year Group from a person. 问题1:我想创建一个程序来收集一个人的姓名,年龄和年份。 I then want to save this into a nested loop. 然后,我想将其保存到嵌套循环中。

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)

So I tried this... 所以我尝试了这个

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

I want the result to look like... 我希望结果看起来像...

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

Problem 2: I wish to then save and read from a File. 问题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)

It then comes up with the problem of "write()" only using strings. 然后出现仅使用字符串的“ write()”问题。 How can easily save this information so when I'm given a name I can use it to find the 2 numbers related to it? 如何轻松保存此信息,以便在获得名称后可以使用它来查找与之相关的2个数字?

Thanks <3 谢谢<3

Problem 1: 问题一:

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

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

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

Problem 2: 问题2:

writing 写作

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

reading

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))

If you don't mind to save as a CSV file, then you can create a Panda data frame with 3 columns using these lists and then save as a CSV file. 如果您不介意另存为CSV文件,则可以使用这些列表创建具有3列的Panda数据框,然后另存为CSV文件。 Later you can read the CSV file and fetch the values of "Age" and "Year" columns based on the value in "Name" column 稍后,您可以读取CSV文件并根据“名称”列中的值获取“年龄”和“年份”列中的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM