如何使用字典创建不同对象的目录

2024-06-09 20:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习使用字典,并试图用它们来做这个具体的事情:

我想要一个用户提示,让用户选择四个项目中的哪一个是水果,然后他们会看到一个类似“鸟,椅子,苹果,草”的列表,他们输入苹果是哪个数字。我想把苹果和许多其他水果放在一本字典里,它们的关键都是“水果”。我还想为不同类型的家具在椅子的一部分和类似的鸟其他字典。这是我可以使用字典的东西还是我走错了方向? 谢谢


Tags: 项目用户苹果类型列表字典数字方向
1条回答
网友
1楼 · 发布于 2024-06-09 20:56:07

你真的可以使用字典,我为你做了一个快速的文件,这样你就可以了解一切的反应。注意:我这样做是为了可读性,对python了解得越多,编写代码的效率就越高

首先定义函数,以便重新调用。然后词汇表就被创建了,不需要把它们放在函数中,但是再放一次;可读性

有些选项是打印的\n插入一个enter。这样你就不会有4个打印语句在彼此下面了。 然后问一个问题int(input("text"))确保给出的答案是整数,而不是基数10

然后是一个简单的if question == 1:,它告诉程序当question = int(input())为1时要做什么

希望你觉得这有帮助,这就是你的意思。如果没有,请随意评论,我会尽力帮助你

def quiz():
    Birds = {'Eagle', 'Parrot', 'Woodpecker', 'Sparrow', 'Pigeon'}
    Furniture = {'Chair', 'Bench', 'Sofa', 'Closet', 'Table'}
    Fruit = {'Apple', 'Cherry', 'Pear', 'Grape', 'Strawberry'}
    Plants = {'Sunflower', 'Cactus', 'Moss', 'Brambles', 'Wheat'}
    print("1. Bird \n2. Chair \n3. Apple \n4. Grass")
    question = int(input("which one is a fruit?: "))
    if question == 1:
        print("Thats wrong! But other kinds of birds are:", ','.join(Birds))
    if question == 2:
        print("Thats wrong! But other kinds of furniture are:", ','.join(Furniture))
    if question == 3:
        print("That's Correct! Other kinds of fruit are:", ','.join(Fruit))
    if question == 4:
        print("Thats wrong! But other kinds of plants are:", ','.join(Plants))

    input("Press Enter to start over")
    quiz()
quiz()

一些来自https://softwareengineering.stackexchange.com/questions/139052/dictionary-vs-list的词典:

You would use a Dictionary if your indexes have a special meaning besides just positional placement.

The immediate example that comes to mind is storing an id column and an int column in a database. For example, if you have a [person-id] column and a [personal-pin] column, then you might bring those into a Dictionary. This way pinDict[person-id] gives you a PIN, but the index is meaningful and not just a position in a List.

But really, any time you have two related lists of integers, this could be an appropriate data structure.

相关问题 更多 >