python列表查找相同字符串_python – 在2D列表中查找最常见的字符串

>用

itertools.chain.from_iterable展平列表

>申请

Counter.

演示:

>>> 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'

细节:

>>> list(chain.from_iterable(lst))

['Mohit',

'shini',

'Manoj',

'Mot',

'Mohit',

'shini',

'Manoj',

'Mohit',

'Vis',

'Nusrath']

>>> Counter(chain.from_iterable(lst))

Counter({'Manoj': 2, 'Mohit': 3, 'Mot': 1, 'Nusrath': 1, 'Vis': 1, 'shini': 2})

>>> Counter(chain.from_iterable(lst)).most_common(1)

[('Mohit', 3)]

一些时间:

>>> 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的第二个解决方案比第一个解决方案慢一点,但内存效率更高.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值