python 列表按第一个字符分组

标签 python python-itertools divide

list1=['hello','hope','hate','hack','bit','basket','code','come','chess']

我需要的是:

list2=[['hello','hope','hate','hack'],['bit','basket'],['code','come','chess']]

如果第一个字符相同并且是同一组,则将其子列表。

我该如何解决这个问题?

最佳答案

您可以使用 itertools.groupby :

>>> from itertools import groupby
>>> list1 = ['hello','hope','hate','hack','bit','basket','code','come','chess']
>>> [list(g) for k, g in groupby(list1, key=lambda x: x[0])]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']]

关于python 列表按第一个字符分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17876130/

相关文章:

java - 如何在其他单词的字符串中将逗号插入到数字中

java - BigDecimal 1.0E+8/100000000 ROUND_HALF_UP 为 0

Java除法运算异常

python - 使用 python 和 postgres,execute 函数中的变量?

python - 使用 pydoc 将模块索引写入文件,无需服务器

python - 在python中用一个列表生成两组组合

python - chain(*iterable) 与 chain.from_iterable(iterable) 之间的区别

python - Django + Postgres : save JSON string directly into model as JSON type

python - django 应用程序的多个实例,django 是否支持这个

python:在某个值之前将字符串列表拆分为多个列表