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

我需要的是:

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

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

我该如何解决这个问题?

4

4 回答 4

12

您可以使用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']]
于 2013-07-26T08:08:02.850 回答
1

扩展 TerryA 的答案:

要创建一个以第一个字母为键、匹配元素为值的字典,您可以这样做

>>> list1=['hello','hope','hate','hack','bit','basket','code','come','chess', 'archetype', 'cheese']
... mydict={}
... for k, g in groupby(list1, key=lambda x: x[0]):
...    if k in mydict:
...        mydict[k] += g
...    else:
...        mydict[k]=list(g)
... print(mydict)
{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'a': ['archetype'], 'c': ['code', 'come', 'chess', 'cheese']}

如果 list1 未排序(如图所示),这也有效,当然,它也可以再次转换为列表列表

>>> [v for k, v in mydict.items()]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['archetype'], ['code', 'come', 'chess', 'cheese']]
于 2017-04-06T19:44:07.047 回答
0

You can do that with partition_by function from my funcy library:

from funcy import partition_by
list2 = partition_by(0, list1)

Note that this will only work if list1 is already sorted, as with itertools.groupby. If list1 is unsorted than sorting it and then partitioning would be inefficient, the better way would be to use group_by function:

from funcy import group_by
list2 = group_by(0, list1).values()
于 2014-06-04T19:27:08.657 回答
0

在 Python 3.7+(即字典维护插入顺序的版本)中,您可以简单地使用以第一个字符为键的列表的字典来对单词进行分组。这适用于已排序和未排序的输入:

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

for word in list1:
    d.setdefault(word[0], []).append(word)
list2 = list(d.values())
print(list2)
# [['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']]
于 2019-10-10T13:18:54.000 回答