python - 如何按照特定模式对字符串列表进行排序

标签 python list sorting design-patterns

我想对每个字符串列表进行排序,例如:

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']

我尝试使用 sorted 方法,但没有成功!

有什么帮助吗?

最佳答案

你可以定义一个key函数,它按要求的顺序返回元组,然后将函数传递给sortedkey参数,比如所以。

>>> 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']

关于python - 如何按照特定模式对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10143515/

相关文章:

python - 将数据框 reshape 为多索引

algorithm - 寻找时间和空间复杂度

mongodb - 在 spring-data mongodb 中对数组进行排序

python - Pandas 的表现就像两个有条件的数据帧的计数一样

python - 我怎样才能在轴上绘制

python - 在类初始化时发出 HTTP 请求

Python 虚拟机参数

java - 如何在 Java 中使用 Comparables 创建自定义参数化列表对象?

c# - 如何根据整数字段获取 List<> 中的项目?

c++ - 优先队列排序 [C++]