2016-04-27 15 views
0

我需要找出哪些行不是相同的长度,但我所拥有的代码是说,所有不是最常见的单词的行是一个不常见的长度,即使他们是确实长度相同。这是我的代码。找到一个不寻常的长度列表

import collections 


fle= ['hello', 'hello', 'hello','justi', 'hello','no', 'hello', 'no'] 


count= sum(1 for n in fle) 
print count 

most_common_length = collections.Counter(fle).most_common(1)[0][0] 
print most_common_length 

mcl = len(most_common_length) 

uncommon = [n for n, v in enumerate(fle) if v != most_common_length] 
print uncommon 

回答

0
此行

uncommon = [n for n, v in enumerate(fle) if v != most_common_length] 

您有效防止“你好”,而不是这个词的长度最常见单词的长度进行比较数组中比较每个字

。它应该是

uncommon = [n for n, v in enumerate(fle) if len(v) != mcl] 

然后输出将是[5,7]它告诉你在索引5和7的单词有不常见的长度。

+0

我想这和它的工作,但现在我改变了一点,现在没有的话是一样的,但有些人仍然有5个字母相同的长度,当我做到这一点,说没有是最常用的长度 –

+0

如果它有效,那么在这里的标准程序是在接受答案。 – e4c5

0
most_common_length = collections.Counter(fle).most_common(1)[0][0] 

你是误导变量名称的受害者。 most_common_length是不是。它实际上是最常见的单词。请注意0​​系列中没有拨打电话len。它不包括字的长度,它是数字。

修复这条线并计算长度很重要。不要试图通过计算结果的长度来解决不好的搜索问题,这就是你在用mcl所做的事情。最常见的词的长度不一定与最常见的长度相同。

uncommon = [n for n, v in enumerate(fle) if v != most_common_length] 

一旦你解决了,你会发现另一个问题。最后比较v与最常见的长度。它应该是len(v)。你想比较长度和长度。

0

获取的平均长度和打印低于平均水平的:

fle = ['hello', 'hello', 'hello','justi', 'hello','no', 'hello', 'no'] 
avg = sum([len(x) for x in fle])/len((fle)) 
print "The following items appear to have an uncommon length: {}".format(', '.join([x for x in fle if len(x) < avg])) 

输出:

The following items appear to have an uncommon length: no, no 
0

您必须比较长不

uncommon = [n for n, v in enumerate(fle) if v != most_common_length] 

另外你可以使用过滤器

uncommon = list(filter(lambda x:len(x) != most_common_length, fle))