为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

米脂 2023-02-15 15:07:54
我正在做一种测验,想知道如何将结果与文本文件进行比较。在根据提示输入回答问题后,该函数将返回一个四位数代码。我希望将该四位数代码与我写出的文本文件中的“truecode”进行比较,并提供如下附加信息:villagername,personality,birthday,zodiac,truecode,speciesAnkha,snooty,September 22nd,Virgo,A420,CatBangle,peppy,August 27th,Virgo,A330,TigerBianca,peppy,December 13th,Sagittarius,A320,TigerBob,lazy,January 1st,Capricorn,A210,CatBud,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!")我不知道如何提取这些信息并将其与我所拥有的进行比较。我应该使用列表还是字典?试图用谷歌搜索我的问题并想知道我是否完全错误地解决了这个问题,我感到很沮丧。我如何将四位数代码(将从另一个函数返回)与“真实代码”进行比较,并像上面那样吐出所有内容?
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

import csv



def get_data(filename):

    with open(filename) as f:

        reader = csv.DictReader(f, delimiter=',')

        data = {row['truecode']: row for row in reader}


    return data



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


查看完整回答
反对 回复 2023-02-15
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

import csv

def 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!")

           break


compare_codes('A420')

上面的代码读取文本文件并将输入与文件中的 truecode 值进行比较并显示信息。


查看完整回答
反对 回复 2023-02-15
?
慕运维8079593

TA贡献1876条经验 获得超5个赞

您拥有的文件类型实际上称为 CSV 文件。如果愿意,您可以使用任何电子表格程序打开您的文本文件,您的数据将显示在相应的单元格中。使用csv 模块读取数据。


import csv


def 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 模块会将文件的每一行转换为使用逗号作为分隔符的字典。第一行很特殊,用于创建字典键。


查看完整回答
反对 回复 2023-02-15
  • 3 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信