【问题标题】:Python dictionary: Changing one value for a dictionary key in a loop changes every value for every key instead [duplicate]Python字典:在循环中更改字典键的一个值会更改每个键的每个值[重复]
【发布时间】:2022-01-02 05:45:45
【问题描述】:

我有一个字符列表。我想将标点符号从列表中拉出,并使每种标点符号成为字典中的键(因此“。”的键,“!”的键等)然后,我想数一下数字每个标点符号出现在另一个列表中的次数,并计算相应键的值。问题是,我的字典中的每个值都会发生变化,而不仅仅是一个键。

输出应该是这样的,因为有 2 个“.”和 4 个“!”在“标点符号列表”中

{'.': [2], ',': [0], '!': [4], '?': [0]}

但是看起来像这样,因为“!”出现 4 次

{'.': [4], ',': [4], '!': [4], '?': [4]}

# Create a list of characters that we will eventually count
charList = [".","!",".","!","!","!","p","p","p","p","p"]

# Create a list of the punctuation we want a count of
punctuationList = [".",",","!","?"]

# Group each type of punctuation and count the number of times it occurs

dic = dict.fromkeys(punctuationList,[0]) # Turn punctuationList into a dictionary with each punctuation type as a key with a value that is 
                                         # the count of each time the key appears in newList

print (dic)

# Count each punctuation in the dictionary

for theKey in dic: # iterate through each key (each punctuation type)
    counter = 0  # Set the counter at 0
    
    for theChar in charList: # If the key matches the character in the list, then add 1 to the counter
        if theKey == theChar:
            
            counter = counter + 1
            
            dic[theKey][0] = counter # Then change the value of that key to the number of times 
                                                   # that character shows up in the list

print (dic)

【问题讨论】:

    标签: python loops dictionary


    【解决方案1】:

    dict.fromkeys 为每个键共享相同的值。

    你会想要的

    dic = {key: [0] for key in punctuationList}
    

    而是为每个键初始化一个单独的列表。 (顺便说一句,确实没有必要将数字包装在列表中。)

    也就是说,您的代码可以使用内置的collections.Counter 来实现

    from collections import Counter
    dic = dict(Counter(ch for ch in charList if ch in punctuationList))
    

    【讨论】:

    • 零怎么办? @AKX
    • @Vishnudev 如果有关系,{**dict.fromkeys(punctuationList, 0), **Counter(...)}
    猜你喜欢
    • 2018-12-05
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多