Python 列表元素出现2次以上
我有努比Python 列表元素出现2次以上,python,python-3.x,Python,Python 3.x,我有努比 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次以上。
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次以上。您需要测试计数器中的最高计数是否大于2;您可以使用提取最高计数:
if Counter(a).most_common(1)[0][1] > 2:
[x for x,y in Counter(a).items() if y > 2]
Counter.most_common()
返回(值、计数)
对的列表,即使您只要求一对[0]
从列表中获取一个(值,计数)
对,然后[1]
提取计数。获取元素列表在数据集中出现两次以上
[x for x,y in Counter(a).items() if y > 2]
您有一个列表,而不是任何
numpy
数组。您的预期结果是什么?仅仅是一个正确或错误的结果,或者您是否也必须让元素出现两次以上?