我有一个二维列表:
arr = [['Mohit', 'shini','Manoj','Mot'],
['Mohit', 'shini','Manoj'],
['Mohit', 'Vis', 'Nusrath']]
我希望在2D列表中找到最常见的元素。在上面的示例中,最常见的字符串是
'Mohit'
。我知道我可以使用两个for循环和一个字典来进行蛮力计算,但是否有更有效的方法使用numpy或任何其他库?
嵌套列表的长度可能不同。
还能有人添加他们方法的时间吗?以找到最快的方法。也需要说明它可能不太高效的限制。
编辑
这是我的系统上不同方法的时间:
#timegb
%%timeit
collections.Counter(chain.from_iterable(arr)).most_common(1)[0][0]
5.91 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#Kevin Fang and Curious Mind
%%timeit
flat_list = [item for sublist in arr for item in sublist]
collections.Counter(flat_list).most_common(1)[0]
6.42 µs ± 501 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
c = collections.Counter(item for sublist in arr for item in sublist).most_common(1)c[0][0]
6.79 µs ± 449 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#Mayank Porwal
def most_common(lst):
return max(set(lst), key=lst.count)
%%timeit
ls = list(chain.from_iterable(arr))
most_common(ls)
2.33 µs ± 42.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#U9-Forward
%%timeit
l=[x for i in arr for x in i]
max(l,key=l.count)
2.6 µs ± 68.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
马扬克·波尔沃的方法在我的系统上运行速度最快。
arr
这个名称,因为这是一个列表,而arr
这个名称通常暗示着array.array
或者numpy.array
。 - timgeb