模拟argmax用于多维数组列表(PYTHON)

时间:2022-04-30 21:33:57

Is there an efficient way of finding the element that occurs most often in a list given that the element is an array of length 2?

鉴于元素是长度为2的数组,是否有一种有效的方法来查找列表中最常出现的元素?

Example:

l = [(1,0),(1,0),(1,1),(0,0),(1,0)]

I would like this to return: (1,0) as that appears the most often.

我希望这返回:(1,0)因为最常出现。

Appears simple but I can't find a way to do this.

看似简单,但我找不到办法做到这一点。

1 个解决方案

#1


2  

You could use collections.Counter

你可以使用collections.Counter

>>> import collections
>>> l = [(1,0),(1,0),(1,1),(0,0),(1,0)]
>>> c = collections.Counter(l)
>>> c.most_common(1)
[((1, 0), 3)]

Otherwise you can use max with a lambda as the key argument

否则,您可以使用max和lambda作为关键参数

>>> max(l, key = lambda i: l.count(i))
(1, 0)

#1


2  

You could use collections.Counter

你可以使用collections.Counter

>>> import collections
>>> l = [(1,0),(1,0),(1,1),(0,0),(1,0)]
>>> c = collections.Counter(l)
>>> c.most_common(1)
[((1, 0), 3)]

Otherwise you can use max with a lambda as the key argument

否则,您可以使用max和lambda作为关键参数

>>> max(l, key = lambda i: l.count(i))
(1, 0)