Python 模式中的排序列表
我目前有一个名为items的列表。我使用Python 模式中的排序列表,python,python-3.x,Python,Python 3.x,我目前有一个名为items的列表。我使用items.sort()以升序获取它们,但我需要所需的输出。在python中有没有简单而容易的方法 items = ['hat1', 'mat3', 'bat2', 'bat1', 'hat2', 'mat4', 'hat5', 'hat6', 'mat1'] 当前O/p- bat1, bat2, hat1, hat2, hat5, hat6, mat1, mat3, mat4 所需O/p- bat1, bat2 hat1, hat2, hat5, h
items.sort()
以升序获取它们,但我需要所需的输出。在python中有没有简单而容易的方法
items = ['hat1', 'mat3', 'bat2', 'bat1', 'hat2', 'mat4', 'hat5', 'hat6', 'mat1']
当前O/p-
bat1, bat2, hat1, hat2, hat5, hat6, mat1, mat3, mat4
所需O/p-
bat1, bat2
hat1, hat2, hat5, hat6
mat1, mat3, mat4
使用
itertools.groupby
:
from itertools import groupby
items = ['hat1', 'mat3', 'bat2', 'bat1', 'hat2', 'mat4', 'hat5', 'hat6', 'mat1']
for k, g in groupby(sorted(items), key=lambda x: x[:3]):
print(list(g))
# ['bat1', 'bat2']
# ['hat1', 'hat2', 'hat5', 'hat6']
# ['mat1', 'mat3', 'mat4']
如果要将其作为一个完整的列表保存,
排序
可以:
sorted(items, key=lambda x:(x[:3], int(x[-1])))
输出:
['bat1', 'bat2', 'hat1', 'hat2', 'hat5', 'hat6', 'mat1', 'mat3', 'mat4']
输出是列表列表吗?它是按字典顺序排序的吗?对于items.sort(),是按字母顺序排序的,只需
排序(items)
即可获得输出,与OP当前的排序相同。他更想要的是将他们分组。