2017-08-06 80 views
-1

我有NumPy的列表元素出現2次以上

from collections import Counter 
import NumPy as np 
a = [ 'abc', 'abc','bca','fdf','dfd','abc','bca','bca'] 

我用

if Counter (a) > 2: 
    print (a) 

Type Error: '>' not supported between instances of 'Counter' and 'int' 

我想輸出是元素的列表數據集中出現的2倍以上。

+1

你有一個列表,不是任何'numpy'數組。 –

+0

你的預期結果*會是什麼?只是一個真實或錯誤的結果,或者你是否必須擁有出現兩次以上的元素? –

回答

0

您需要測試計數器中的最高計數是否大於2;您可以使用Counter.most_common()提取最高計數:

if Counter(a).most_common(1)[0][1] > 2: 

Counter.most_common()返回(value, count)對列表,甚至當你問的只是一對; [0]從列表中獲取一個(value, count)對,並且[1]提取計數。

1

獲取元素列表在數據集中出現超過2次。

[x for x,y in Counter(a).items() if y > 2] 
+0

它工作得很好,非常感謝 –

相關問題