字典键值只显示唯一的结果,而不是所有结果

2024-10-06 06:52:36 发布

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

我有corpus_test然后我将他升级到用单词分割的列表。我需要有2dictionarys从这个和len的文字。问题是唯一值。我需要所有的,甚至是副本

corpus_test = 'cat dog tiger tiger tiger cat dog lion'
corpus_test = [[word.lower() for word in corpus_test.split()]]
word_counts = defaultdict(int)
for rowt in corpus_test:
    for wordt in rowt:
        word_counts[wordt] += 1



        index_wordso = dict((i, word) for i, word in enumerate(rowt))

        word_indexso = dict((word, i) for i, word in enumerate(rowt)) 

        v_countso = len(index_wordso)

我的代码通过index_wordsov_countso为我提供了正确的输出:

index_wordso
#{0: 'cat',
 1: 'dog',
 2: 'tiger',
 3: 'tiger',
 4: 'tiger',
 5: 'cat',
 6: 'dog',
 7: 'lion'}


v_countso
#8

但是word_indexso(逆dictindex_wordso)给了我不正确的输出:

word_indexso
#{'cat': 5, 'dog': 6, 'tiger': 4, 'lion': 7}

这只是给我最后的值,不是全部。我需要全部8个值


Tags: intestforindexcorpusdictcatword
1条回答
网友
1楼 · 发布于 2024-10-06 06:52:36

字典中的键是唯一的,值不是唯一的。它就像一本单词词典:一个单词可以有多个定义,但不能有多个单词列表

解决方法是使用元组列表:

corpus_test = 'cat dog tiger tiger tiger cat dog lion'
corpus_test = [word.lower() for word in corpus_test.split()]
print([(a,b) for (a, b) in zip(corpus_test, range(len(corpus_test)))])

导致

[('cat', 0),
 ('dog', 1),
 ('tiger', 2),
 ('tiger', 3),
 ('tiger', 4),
 ('cat', 5),
 ('dog', 6),
 ('lion', 7)]

但是请记住,这不是一个查找表,因此您必须(以某种方式)遍历元素以查找特定元素

另一种方法是使用列表字典:

from collections import defaultdict

word_indexso = defaultdict(list)
corpus_test = 'cat dog tiger tiger tiger cat dog lion'.split()

for index, word in enumerate(corpus_test):
    word_indexso[word].append(index)

print(word_indexso)

导致

defaultdict(<class 'list'>, {'cat': [0, 5], 'dog': [1, 6], 'tiger': [2, 3, 4], 'lion': [7]})

可以使用例如word_indexso["cat"]来查找,以获得与该单词相关联的数字列表

相关问题 更多 >