我想对每个字符串列表进行排序,例如:
list1 = ['3DT1_PN_DIS3D_S001', '3DT1_PN_noDIS3D_S001', '3DT1_S001', '3DT1_noPN_DIS3D_S001']
list2 = ['3DT1_noPN_DIS3D_S002', '3DT1_PN_noDIS3D_S002', '3DT1_PN_DIS3D_S002']
遵循模式[‘3DT1_S ##’,’3DT1_noPN_DIS3D_S ##’,’3DT1_PN_noDIS3D_S ##’,’3DT1_PN_DIS3D_S ##’]
结果应该是:
list1 = [ '3DT1_S001', '3DT1_noPN_DIS3D_S001', '3DT1_PN_noDIS3D_S001', '3DT1_PN_DIS3D_S001']
list2 = [ '3DT1_noPN_DIS3D_S002', '3DT1_PN_noDIS3D_S002', '3DT1_PN_DIS3D_S002']
我尝试使用排序方法,但是没有运气!
有什么帮助吗?
解决方法:
您可以定义一个按要求的顺序返回元组的键函数,然后将该函数传递给排序的键参数,如下所示.
>>> def key_fn(x):
... tags = x.split('_')
... if tags[1][0] == 'S':
... return (0, int(tags[1][1:]))
... elif tags[1] == 'noPN':
... return (1, int(tags[3][1:]))
... elif tags[1] == 'PN':
... if tags[2] == 'noDIS3D':
... return (2, int(tags[3][1:]))
... else:
... return (3, int(tags[3][1:]))
...
>>> list1 = ['3DT1_PN_DIS3D_S001', '3DT1_PN_noDIS3D_S001', '3DT1_S001', '3DT1_noPN_DIS3D_S001']
>>> sorted(list1, key=key_fn)
['3DT1_S001', '3DT1_noPN_DIS3D_S001', '3DT1_PN_noDIS3D_S001', '3DT1_PN_DIS3D_S001']