2016-11-05 50 views
0
# -*- 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 

输出不正确。我的代码有什么问题。输出似乎为什么打印出错误的结果。 python enumerate,计数器

[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']

+4

它有什么问题?准确地说明你预期的产出*。 –

回答

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)。

+1

我的输出是[0,6,12,27] [16,17,18,19,20,21,22,23,24] [2,8,14,29] [1,7,13 ,28]每一个最后的号码都是错误的。它显示0,6,12作为“它”和27“智慧” – Dnr

+0

我看到了。请注意,这个输出是完全正确的;在你的行尾添加逗号更喜欢Python不为你串联字符串。 – alf

+0

谢谢。我看到了 。没有两个逗号。 – Dnr

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风格的指南也有长度限制(尽管它们通常是对于字符的确切数量,它更慷慨一些)。