为什么我所有的字典值都打印相同的输出?

2024-06-08 04:32:21 发布

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

*编辑 我的目标是打印一个字典(word:count),计算字符列表中的名称出现在行列表中的次数。我尝试更改代码,但它要么将每个不同键的值打印为0,要么打印为1011。这就是我目前所在的位置,打印1011个值。我完全不知所措,只上了几周Python课(使用Python3),如果这毫无意义,我会提前道歉

characters_list = [
    'threepio', 'luke', 'imperial officer', 'vader', 'rebel officer',
    'trooper', 'chief pilot', 'captain', 'woman', 'fixer', 'camie',
    'biggs', 'deak', 'leia', 'commander', 'second officer', 'owen',
    'aunt beru', 'ben', 'tagge', 'motti', 'tarkin', 'bartender',
    'creature', 'human', 'han', 'greedo', 'jabba', 'officer cas',
    'voice over deathstar intercom', 'gantry officer', 'intercom voice',
    'trooper voice', 'first trooper', 'first officer', 'second trooper',
    'officer', 'willard', 'dodonna', 'wedge', 'man', 'red leader',
    'chief', 'massassi intercom voice', 'red ten', 'red seven', 'porkins',
    'red nine', 'red eleven', 'gold leader', 'astro-officer',
    'control officer', 'gold two', 'gold five', 'wingman', 'voice',
    'technician'
    ]
    
    line_list = []
    with open('/Users/user_name/Documents/SW_EpisodeIV.txt', 'r') as my_file:
        for line in my_file:
              line_list.append(line)
        line_list = [each_string.lower() for each_string in line_list]
my_dict = {}
        for  x in range(len(line_list)):
            x += 1
            
            for i in characters_list:
                my_dict[i] = x
        print(my_dict)
main()

Tags: in列表formylinereddictlist
2条回答

考虑到这是您的数据:

words = ['foo', 'bar', 'bak']
words2 = ['foo', 'bar', 'bak', 'foo', 'no']

您可以使用collections.Counter

from collections import Counter

occurences = {k: v for k, v in Counter(words2).items() if k in words}

或者只是一个dict并将words设置为一个集合,这样就不会在重复的单词上循环:

occurences = {}
for word in set(words):
    occurences[word] = occurences.setdefault(key, 0) + words2.count(word)

从变量的名称中不清楚它们的函数是什么,但这里有一个通用的解决方案:

假设您有一个words个值的列表,您希望对这些值的出现次数进行计数,您可以执行以下操作:

counts = {}
for word in words:
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1

然后counts成为您想要的字典(如果需要,您可以稍后过滤它以获得特定的值)

相关问题 更多 >

    热门问题