【发布时间】:2019-04-25 17:43:06
【问题描述】:
我有一个二维列表:
arr = [['Mohit', 'shini','Manoj','Mot'],
['Mohit', 'shini','Manoj'],
['Mohit', 'Vis', 'Nusrath']]
我想在二维列表中找到最常见的元素。在上面的例子中,最常见的字符串是'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)
Mayank Porwal 的方法在我的系统上运行速度最快。
【问题讨论】:
-
您如何定义“频繁”、出现次数最多或出现在最多子列表/行中的次数?
-
在整个二维数组中出现次数最多。
-
对嵌套数组中元素数量 (n) 与嵌套数组数量 (m) 的任何限制。即 m >> n 或 n
-
@bigdata2 不是真的。 2D 列表不太可能很大。甚至是列表中的元素。
-
@MohitMotwani 时间有点取决于列表的长度和其中唯一元素的数量。 max(set... 解决方案对于具有很少唯一元素的列表来说很快
标签: python python-3.x list numpy numpy-ndarray