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

2024-04-29 07:11:40 发布

您现在位置: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!")

我不知道如何提取这些信息,并将其与我所拥有的进行比较。我应该使用列表还是字典?我在谷歌上搜索我的问题时感到很沮丧,我想知道我是不是绕错了方向

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


Tags: 函数代码信息catspeciesbirthdayprint文本文件
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值进行比较,并显示信息

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

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

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

相关问题 更多 >