Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模式中的排序列表_Python_Python 3.x - Fatal编程技术网

Python 模式中的排序列表

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的列表。我使用
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当前的排序相同。他更想要的是将他们分组。