python排序,要把TP312.8排在TP312C,TP312PY后,应该如何写代码
时间: 2024-02-13 17:05:12 浏览: 151
在Python中,可以使用自定义排序规则来实现这个需求。具体操作如下:
```python
# 定义排序规则
def custom_sort(x):
if 'TP312.8' in x:
return 0
elif 'TP312C' in x:
return 1
elif 'TP312PY' in x:
return 2
else:
return 3
# 测试数据
data = ['TP312PY', 'TP312.8', 'TP312C', 'TP123', 'TP312']
# 按照自定义规则排序
sorted_data = sorted(data, key=custom_sort)
# 输出排序结果
print(sorted_data)
```
输出结果为:
```
['TP312.8', 'TP312C', 'TP312PY', 'TP123', 'TP312']
```
以上代码中,我们定义了一个`custom_sort`函数作为排序规则,根据题目要求,将`TP312.8`排在第一,`TP312C`排在第二,`TP312PY`排在第三,其他字符串排在最后。然后使用`sorted`函数,指定`key`参数为`custom_sort`函数,即可按照自定义规则排序。最后输出排序结果。
阅读全文
相关推荐








