我有两个清单如下
x = ['a','a','b','c','b','a']
和
x = ['a','a','b','c','c','d']
我试图找出在每个列表中出现最多的值。这就是我尝试过的。
def unique_values(output,input): for i in input: if i not in output: output.append(i) k = [] for i in k: unique_values(k,x) y.remove(i)
我已经走了这么远,但我想不出如何for i in k:在删除列表中的所有值之前停止的方法。
for i in k:
如果要查找列表中每个元素的出现,可以使用Counterfrom的模块collections:-
Counter
collections
>>> x = ['a','a','b','c','c','d'] >>> from collections import Counter >>> count = Counter(x) >>> count Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1}) >>> count.most_common() [('a', 2), ('c', 2), ('b', 1), ('d', 1)]
因此,前两个元素在您的列表中最常见。
>>> count.most_common()[0] ('a', 2) >>> count.most_common()[1] ('c', 2)
或者,您还传递参数来most_common()指定所需的most-common元素数:-
most_common()
most-common
>>> count.most_common(2) [('a', 2), ('c', 2)]
更新:-
您也可以先找出max计数,然后再找到具有该值的元素总数,然后可以将其用作参数most_common():-
max
>>> freq_list = count.values() >>> freq_list [2, 2, 1, 1] >>> max_cnt = max(freq_list) >>> total = freq_list.count(max_cnt) >>> most_common = count.most_common(total) [('a', 2), ('c', 2)] >>> [elem[0] for elem in most_common] ['a', 'c']