2016-04-27 18 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))