在二维列表中查找最常见的字符串

2024-04-20 01:35:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维列表:

arr = [['Mohit', 'shini','Manoj','Mot'],
      ['Mohit', 'shini','Manoj'],
      ['Mohit', 'Vis', 'Nusrath']]

我想在2D列表中找到最常见的元素。在上面的例子中,最常见的字符串是'Mohit'。在

我知道我可以使用bruteforce使用两个for循环和一个字典来完成这项工作,但是有没有更有效的方法使用numpy或其他任何库呢?在

The nested lists could be of different lengths

有人也可以加上他们的方法的时间吗?找到禁食的方法。此外,还有一些可能不是很有效的警告。在

编辑

以下是系统中不同方法的计时:

^{pr2}$

Mayank Porwal的方法在我的系统上运行最快。在


Tags: 方法字符串元素列表for系统vis例子
3条回答

我建议将二维数组展平,然后使用计数器找出最频繁的元素。在

flat_list = [item for sublist in arr for item in sublist]
from collections import Counter
Counter(flat_list).most_common(1)[0]
# ('Mohit', 3)
Counter(flat_list).most_common(1)[0][0]
# 'Mohit'

但不确定这是否是最快的方法。在

编辑:

@timgeb的答案有一种更快的方法,可以使用itertools.chain将列表变平

@schwobaseggl提出了一种更节省空间的方法:

^{pr2}$
  1. ^{}展开列表
  2. 应用^{}

演示:

>>> from itertools import chain
>>> from collections import Counter
>>> 
>>> lst = [['Mohit', 'shini','Manoj','Mot'],
...:      ['Mohit', 'shini','Manoj'],
...:      ['Mohit', 'Vis', 'Nusrath']]
...:      
>>> Counter(chain.from_iterable(lst)).most_common(1)[0][0]
'Mohit'

详细信息:

^{pr2}$

一些时间安排:

>>> lst = lst*100
>>> %timeit Counter(chain.from_iterable(lst)).most_common(1)[0][0] # timgeb
53.7 µs ± 411 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit max([x for i in lst for x in i], key=l.count) # U9-Forward
207 µs ± 389 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit Counter([x for sublist in lst for x in sublist]).most_common(1)[0][0] # Curious_Mind/Kevin Fang #1
75.2 µs ± 2.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit Counter(item for sublist in lst for item in sublist).most_common(1)[0][0] # Kevin Fang #2
95.2 µs ± 2.07 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit flat = list(chain.from_iterable(lst)); max(set(flat), key=flat.count) # Mayank Porwal
98.4 µs ± 178 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

(请注意,Kevin Fang的第二个解决方案比第一个稍慢一些,但更节省内存。)

这样做的一种方法

import collections
import time
start_time = time.time()
arr = [['Mohit', 'shini','Manoj','Mot'],
      ['Mohit', 'shini','Manoj'],
      ['Mohit', 'Vis', 'Nusrath']]

c = collections.Counter([x for sublist in arr for x in sublist])
print(c.most_common(1) )
print("--- %s seconds ---" % (time.time() - start_time)) 

所用时间:0.00016713142395秒

演示:http://tpcg.io/NH3zjm

相关问题 更多 >