我是 python 的新手,需要一些帮助来找出元组的模式。但是,我现在的代码只显示一种模式,我需要更改什么才能显示多种模式(如果数字列表超过 1 个)
import itertools
import operator
def mode_function2(lst):
return max(set(lst), key=lst.count)
最佳答案
这个有效:
from collections import Counter
def mode_function2(lst):
counter = Counter(lst)
_,val = counter.most_common(1)[0]
return [x for x,y in counter.items() if y == val]
下面是一个演示:
>>> mode_function2([1, 2, 2])
[2]
>>> mode_function2([1, 2, 2, 1])
[1, 2]
>>> mode_function2([1, 2, 3])
[1, 2, 3]
>>>
这里的重要概念是:
关于python - 在元组列表中查找多种模式 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035448/