为什么打印错误的结果。 python枚举,计数器

时间:2016-11-05 22:45:54

标签: python counter enumerate

# -*- coding: utf-8 -*-
from collections import Counter
import itertools, collections
ListeA=['it', 'was', 'the', 'besttttttttttttttrtrtrtrtrttrtr', 'of', 'times', 'it', 'was',
        'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx'
        'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'xx'
        'foolishness']

index = collections.defaultdict(list);

for value, key in enumerate(ListeA):
    index[key].append(value)

for key1,value1 in index.items(): 
    if len(value1)>=4:  
         print value1

输出不正确。我的代码有什么问题。输出似乎

[0, 6, 12, 27]
[16, 17, 18, 19, 20, 21, 22, 23, 24]
[2, 8, 14, 29]
[1, 7, 13, 28]

我添加了数字以便于阅读ListeA=[0'it', 1'was', 2'the', 3'besttttttttttttttrtrtrtrtrttrtr', 4'of', 5'times', 6'it', 7'was', 8'the', 9'worst', 10'of', 11'times', 12'it', 13'was', 14'the', 15'age', 16'xx', 17'xx', 18'xx', 19'xx', 20'xx', 21'xx', 22'xx', 23'xx', 24'xx', 25'xx' 26'of', 27'wisdom', 28'it', 29'was', 30'the', 31'age', 32'of', 33'xx' 34'foolishness']

2 个答案:

答案 0 :(得分:1)

您在列表的行末尾错过了一些逗号。

由于列表项是字符串文字,因此最终会有两个彼此相邻的项目,它们之间没有语法。 Python中一个鲜为人知的特性是相邻的字符串文字被连接起来。因此"foo" "bar""foobar"的字符串相同。这也可以跨越换行符,只要换行不结束表达式(通常是因为它在括号内或某种括号中)。

此问题意味着您的数据中包含"xxof""xxfoolishness",而不是"xx"(两次),"of""foolishness"字符串。它也可能会使你的预期数量减少。

要解决此问题,请在错过的行末尾添加逗号:

ListeA=['it', 'was', 'the', 'besttttttttttttttrtrtrtrtrttrtr', 'of', 'times', 'it', 'was',
    'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'xx', 'xx',
    'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', 'xx', # add comma here
    'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'xx', # and here
    'foolishness']

除了逗号之外,我还添加了一个额外的换行符来打破前一点的最长行,这样整个事物就更有可能同时适应屏幕(没有水平滚动条)。 PEP 8建议代码行长度不超过79个字符,或者72个字符用于文档字符串和注释,可以按照您想要的任何方式重新排列。这只是对Python本身的代码的严格要求(例如对标准库的修复),但是许多人试图在他们自己的代码中遵循PEP 8,并且许多其他Python样式指南也有长度限制(尽管他们& #39;对于确切的字符数,通常会更加慷慨。)

答案 1 :(得分:0)

据我所见,结果是正确的:

>>> for value, key in enumerate(ListeA): print value, key
... 
0 it
1 was
2 the
3 besttttttttttttttrtrtrtrtrttrtr
4 of
5 times
6 it
7 was
8 the
9 worst
10 of
11 times
12 it
13 was
14 the
15 age
16 xx
17 xx
18 xx
19 xx
20 xx
21 xx
22 xx
23 xx
24 xx
25 xxof
26 wisdom
27 it
28 was
29 the
30 age
31 of
32 xxfoolishness
>>> 

您是否完全确定“添加号码以便于阅读”的代码与示例中的代码相同?

请注意,如果您错过了逗号,Python将为您连接字符串(例如,参见条目25和32)。