猿问

Python 使用字典列表?我用什么

我正在做一种测验,想知道如何将结果与文本文件进行比较。在根据提示输入回答问题后,该函数将返回一个四位数代码。我希望将该四位数代码与我写出的文本文件中的“truecode”进行比较,并提供如下附加信息:


villagername,personality,birthday,zodiac,truecode,species

Ankha,snooty,September 22nd,Virgo,A420,Cat

Bangle,peppy,August 27th,Virgo,A330,Tiger

Bianca,peppy,December 13th,Sagittarius,A320,Tiger

Bob,lazy,January 1st,Capricorn,A210,Cat

Bud,jock,August 8th,Leo,A310,Lion

我希望打印出这些其他信息。


    print("Your villager is " + villagername)

    print("They are a " + personality + " type villagers and of the " + species + " species.")

    print("Their birthday is " + birthday + " and they are a " + zodiac)

    print("I hope you enjoyed this quiz!")

我不知道如何提取这些信息并将其与我所拥有的进行比较。我应该使用列表还是字典?试图用谷歌搜索我的问题并想知道我是否完全错误地解决了这个问题,我感到很沮丧。


我如何将四位数代码(将从另一个函数返回)与“真实代码”进行比较,并像上面那样吐出所有内容?


米脂
浏览 131回答 3
3回答

拉莫斯之舞

import csvdef get_data(filename):    with open(filename) as f:        reader = csv.DictReader(f, delimiter=',')        data = {row['truecode']: row for row in reader}    return datadef main():    filename = 'results.txt'    data = get_data(filename)    code = input('Enter code: ')    try:        info = data[code]        print("Your villager is " + info['villagername'])        print("They are a " + info['personality'] +              " type villagers and of the " + info['species'] + " species.")        print("Their birthday is " +              info['birthday'] + " and they are a " + info['zodiac'])        print("I hope you enjoyed this quiz!")    except KeyError:        print('Invalid code')if __name__ == "__main__":    main()

繁星点点滴滴

import csvdef compare_codes(true_code):    with open(''file.txt) as csvfile:        details_dict = csv.reader(csvfile)    for i in details_dict:        if i['truecode'] == tru_code:           print("Your villager is:",i['villagername'])           print("They are a " + i['personality'] + " type villagers and of the " + i['species'] + " species.")           print("Their birthday is " + i['birthday'] + " and they are a " + i['zodiac'])           print("I hope you enjoyed this quiz!")           breakcompare_codes('A420')上面的代码读取文本文件并将输入与文件中的 truecode 值进行比较并显示信息。

慕运维8079593

您拥有的文件类型实际上称为 CSV 文件。如果愿意,您可以使用任何电子表格程序打开您的文本文件,您的数据将显示在相应的单元格中。使用csv 模块读取数据。import csvdef get_quiz_results(truecode):    with open('your-text-file.txt') as csvfile:        csvreader = csv.reader(csvfile)        for row in csvreader:            # row is a dictionary of all of the items in that row of your text file.            if row['truecode'] == truecode:                return row然后打印出文本文件中的信息truecode = 'A330'info = get_quiz_results(truecode)print("Your villager is " + info["villagername"])print("They are a " + info["personality"] + " type villagers and of the " + info["species"] + " species.")print("Their birthday is " + info["birthday"] + " and they are a " + info["zodiac"])print("I hope you enjoyed this quiz!")遍历文件时,csv 模块会将文件的每一行转换为使用逗号作为分隔符的字典。第一行很特殊,用于创建字典键。
随时随地看视频慕课网APP

相关分类

Python
我要回答