How to group similar items in a list?

与世无争的帅哥 提交于 2019-12-04 23:49:04

The .split("_")[0] part should be inside a single-argument function that you pass as the second argument to itertools.groupby.

>>> import os, itertools
>>> test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2']
>>> [list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]
[['abc_1_2', 'abc_2_2'], ['hij_1_1'], ['xyz_1_2', 'xyz_2_2']]
>>>

Having it in the for ... part does nothing since the result is immediately discarded.


Also, it would be slightly more efficient to use str.partition when you only want a single split:

[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]

Demo:

>>> from timeit import timeit
>>> timeit("'hij_1_1'.split('_')")
1.3149855638076913
>>> timeit("'hij_1_1'.partition('_')")
0.7576401470019234
>>>

This isn't a major concern as both methods are pretty fast on small strings, but I figured I'd mention it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!