[英]Saving an nested list into a text file
問題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
問題一:
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))
如果您不介意另存為CSV文件,則可以使用這些列表創建具有3列的Panda數據框,然后另存為CSV文件。 稍后,您可以讀取CSV文件並根據“名稱”列中的值獲取“年齡”和“年份”列中的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.