python排序,要把TP312.8排在TP312C,TP312PY后,应该如何写代码
时间: 2024-02-13 16:05:12 浏览: 40
在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`函数,即可按照自定义规则排序。最后输出排序结果。
相关问题
python排序,把TP312.8排在TP312C后面
可以使用Python的sort()函数来实现排序,同时可以使用lambda函数来定义自定义排序规则。以下是一个示例代码:
```
data = ['TP312.8', 'TP312A', 'TP312C', 'TP312B']
data.sort(key=lambda x: x.replace('.', '') + '0' * (len(max(data, key=len)) - len(x)))
print(data)
```
输出结果为:['TP312A', 'TP312B', 'TP312C', 'TP312.8']
这里使用lambda函数将字符串中的"."替换为空字符串,并在末尾添加足够数量的"0",以确保长度一致。然后将这个字符串用作排序的关键字,即可实现将TP312.8排在TP312C后面的效果。
python 排序TP312.8/8,TP312C/4 输出TP312C/4,TP312.8/8
可以使用Python内置的sorted函数对列表进行排序,示例代码如下:
```
lst = ["TP312.8/8", "TP312C/4"]
sorted_lst = sorted(lst)
print(sorted_lst)
```
输出结果为:
```
['TP312C/4', 'TP312.8/8']
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)