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

Python 字典键值只显示唯一的结果,而不是所有结果,python,Python,我有corpus\u测试,然后我将他升级到单词分割列表。我需要这两本字典和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 wor

我有
corpus\u测试
,然后我将他升级到单词分割列表。我需要这两本
字典和
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\u wordso
v\u countso
为我提供了正确的输出:

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


v_countso
#8
但是
word\u indexso
(逆
dict
index\u wordso
)给了我不正确的输出:

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

这只是给我最后的值,不是全部。我需要字典中的所有8个值都是唯一的,值不是唯一的。它就像一本单词词典:一个单词可以有多个定义,但不能有多个单词列表

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

corpus_test='cat-dog-tiger-tiger-cat-dog-lion'
语料库测试=[word.lower()表示语料库测试中的单词.split()]
打印([(a,b)用于(a,b)的zip格式(语料库测试,范围(len(语料库测试)))]
导致

[('cat',0),
('dog',1),
(‘老虎’,2),
(‘老虎’,3),
(‘老虎’,4),
('cat',5),
('dog',6),
('lion',7)]
但是请记住,这不是一个查找表,因此您必须(以某种方式)遍历元素以查找特定元素

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

从集合导入defaultdict
word_indexso=defaultdict(列表)
语料库测试=‘猫狗老虎猫狗狮子’。拆分()
对于索引,枚举中的单词(语料库测试):
word_indexso[word]。追加(索引)
打印(word_indexso)
导致

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

可以使用例如
word_indexso[“cat”]
来查找与该单词相关联的数字列表。

可以使用元组列表,也可以使用字典列表?字典键是唯一的。如果他们不是你,你将能够做
word_indexso['tiger']
,并得到一个合理的结果。(应该返回
2
3
,还是
4
?)嗯,是这样,所以我不能用python做任何事情?“这只是一个基本的问题吗?”germanjke我意识到我的答案不是一个真正的答案,对此我很抱歉。受AMC启发,请参见我的更新答案。@Germanyke,Python不是一种“基础”语言:)您只需考虑问题以及哪些数据结构最好。