简体   繁体   English

Python:将用户输入作为列表添加到字典中

[英]Python: adding user input as a list to dictionary

I have the following script.我有以下脚本。 I ask the user for categories and every category can be sorted in a couple of different ways also given by the user.我向用户询问类别,每个类别都可以按用户提供的几种不同方式进行排序。 The output should thus be something like:因此,输出应类似于:

{'a': ['b', 'c'], 'd': ['e', 'f']}

But it comes:但它来了:

{'a': ['b', 'c', 'e', 'f'], 'd': ['b', 'c', 'e', 'f']}

I think that it's because i refer to the same list in each category.我认为这是因为我在每个类别中都引用了相同的列表。 I don't really know how to make it dynamic and clearing the list afterwards doesn't seem to give to proper result either.我真的不知道如何使其动态化,之后清除列表似乎也没有给出正确的结果。

Can someone point me in the right direction?有人可以指出我正确的方向吗? Thanks in advance提前致谢

def user_settings():
    settings = {}
    sorteer = []
    while True:

        categorie = input('wat wordt de naam van de categorie: \n')
        if categorie == 'q':
            break
        while True:
            sorteren = input('waar wil je op sorteren: \n')
            if sorteren == 'q':
                break
            sorteer.append(sorteren)
            settings[categorie] = sorteer
    print(settings)

In python lists are mutable and you are using sorteer list against keys in settings dict.在 python 中列表是可变的,并且您正在对设置字典中的键使用排序器列表。 Every time you make a change in list(adding or removing element) it reflects against each key as you are using the same list.每次在列表中进行更改(添加或删除元素)时,它都会反映在您使用相同列表的每个键上。 For detailed understanding refer: Does Python have an immutable list?详细理解请参考: Does Python have an immutable list?

You can change your program to:您可以将程序更改为:

   def user_settings():
    settings = {}
    while True:
        categorie = input('Enter category: \n')
        if categorie == 'q':
            break
        while True:
            sorteren = input('enter range: \n')
            if sorteren == 'q':
                break
            if categorie in settings: #for python2.X use if settings.has_key(categorie)
                settings[categorie].append(sorteren)
            else:
                settings[categorie]=[sorteren]
    print(settings)

user_settings()

Output: {'a': ['b', 'c'], 'd': ['e', 'f']}输出: {'a': ['b', 'c'], 'd': ['e', 'f']}

tl;dr move sorteer = [] one line down, so that it's inside the while-loop tl; dr move sorteer = []向下一行,以便它在while循环内

def user_settings():
    settings = {}
    while True:
        sorteer = []
        categorie = input('wat wordt de naam van de categorie: \n')
        if categorie == 'q':
            break
        while True:
            sorteren = input('waar wil je op sorteren: \n')
            if sorteren == 'q':
                break
            sorteer.append(sorteren)
            settings[categorie] = sorteer
    print(settings)

Explanation: sorteer = [] creates a new list.解释: sorteer = []创建一个新列表。 Unfortunately, you only do that once.不幸的是,你只能这样做一次。 It means you have just 1 list.这意味着您只有 1 个列表。 Not only all the values of your dictionary have the same elements, but they are exactly the same object:不仅字典的所有值都具有相同的元素,而且它们是完全相同的对象:

>>> sorteer['a'] == sorteer['d']
True
>>> sorteer['a'] is sorteer['d']
True

sorteer.append(sorteren) doesn't create a copy of the list. sorteer.append(sorteren)不会创建列表的副本。 So all the keys are mapped to the only list you have, the one you created at the beginning.因此,所有键都映射到您拥有的唯一列表,即您在开始时创建的列表。

The easiest way to fix your code is to create a new list every time you start a new loop of while .修复代码的最简单方法是在每次启动新的while循环时创建一个新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM