【发布时间】: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