Python遍历两个列表仅遍历最后一个元素

时间:2018-11-14 14:05:14

标签: python list dictionary

我正在尝试遍历双重列表,但得到的结果不正确。我正在尝试获取列表中每个元素的数量。

l = [['<s>', 'a', 'a', 'b', 'b', 'c', 'c', '</s>'], ['<s>', 'a', 'c', 'b', 'c', '</s>'], ['<s>', 'b', 'c', 'c', 'a', 'b', '</s>']]

dict = {}

for words in l:
    for letters in words:
        dict[letters] = words.count(letters)


for x in countVocabDict:
        print(x + ":" + str(countVocabDict[x]))

此刻,我得到:

<s>:1
a:1
b:2
c:2
</s>:1

似乎只在'l' : ['<s>', 'b', 'c', 'c', 'a', 'b', '</s>']中的最后一个列表中进行迭代

但是我想得到:

<s>: 3
a: 4
b: 5
c: 6
</s>:3

4 个答案:

答案 0 :(得分:2)

在每个内部for循环中,您没有添加到dict[letters]的当前值,而是将其设置到命名为当前子列表(特别是)的任何数量word

使用普通dict修复代码:

>>> l = [['<s>', 'a', 'a', 'b', 'b', 'c', 'c', '</s>'], ['<s>', 'a', 'c', 'b', 'c', '</s>'], ['<s>', 'b', 'c', 'c', 'a', 'b', '</s>']]
>>> d = {}                                                                  
>>>
>>> for sublist in l: 
...:     for x in sublist: 
...:         d[x] = d.get(x, 0) + 1 
>>> d                                                                       
{'<s>': 3, 'a': 4, 'b': 5, 'c': 6, '</s>': 3}

请注意,我没有在每个内部list.count循环中调用for。调用count将一次又一次遍历整个列表。每次看到一个值时仅添加1的效率要高得多,这可以通过仅一次查看(子)列表中的每个元素来完成。

使用Counter

>>> from collections import Counter                                         
>>> Counter(x for sub in l for x in sub)                                    
Counter({'<s>': 3, 'a': 4, 'b': 5, 'c': 6, '</s>': 3})

使用Counter而不是手动取消嵌套列表的嵌套:

>>> from collections import Counter                                         
>>> from itertools import chain                                        
>>> Counter(chain.from_iterable(l))                                         
Counter({'<s>': 3, 'a': 4, 'b': 5, 'c': 6, '</s>': 3})

答案 1 :(得分:1)

字典在每次迭代中都会被覆盖,而应该更新

count_dict[letters] += words.count(letters)

使用defaultdict初始化字典

from collections import defaultdict
count_dict = defaultdict(int)

答案 2 :(得分:0)

正如@Vishnudev所说,您必须添加当前计数器。但是dict[letters]必须存在(否则您将获得KeyError异常)。您可以使用具有默认值的get dict方法来避免这种情况:

l = [['<s>', 'a', 'a', 'b', 'b', 'c', 'c', '</s>'], 
     ['<s>', 'a', 'c', 'b', 'c', '</s>'], 
     ['<s>', 'b', 'c', 'c', 'a', 'b', '</s>']]

dict = {}
for words in l:
    for letters in words:
        dict[letters] = dict.get(letters, 0) + 1

答案 3 :(得分:0)

根据您的问题,您似乎知道它仅采用最后一个子列表的结果。发生这种情况是因为在每次迭代之后,您先前的词典值都会被下一个迭代值替换并覆盖。因此,您需要维护以前的状态值,并将其添加到新计算的值中。

您可以试试这个-

l = [['<s>', 'a', 'a', 'b', 'b', 'c', 'c', '</s>'], ['<s>', 'a', 'c', 'b', 'c', '</s>'], ['<s>', 'b', 'c', 'c', 'a', 'b', '</s>']]
d={}
for lis in l:
    for x in lis:
        if x in d:
            d[x]+=1
        else:
            d[x]=1

因此,结果字典d将为-

{'<s>': 3, 'a': 4, 'c': 6, 'b': 5, '</s>': 3}

我希望这会有所帮助!

相关问题