python - 如何在python中对轮胎尺寸进行排序

标签 python list sorting

我正在尝试从最小到最大对(字符串)轮胎尺寸列表进行排序。

['285/30/18',
 '285/30/19',
 '235/40/17',
 '315/25/19',
 '275/30/19']

应该排序为:

['235/40/17',
 '285/30/18',
 '315/25/19'
 '275/30/19',
 '285/30/19']

我基本上必须从右边开始对字符串进行排序,中间然后左边。

到目前为止我有什么(冒泡排序):

# this sorts the first numbers on the right.
nums = list(ulst)
for i in range(len(nums)):
     for j in range(i+1, len(nums)):
         if ulst[j].split('/')[2] < ulst[i].split('/')[2]:
             ulst[j], ulst[i] = ulst[i], ulst[j]

我现在必须在不弄乱右行排序的情况下对中间进行排序,然后对左行进行排序....

如何在不造成 for/if 嵌套困惑的情况下解决这个问题?

最佳答案

Python 有几个特性可以让这件事变得容易。事实上,您可以在一条语句中完成所有操作:

sorted(nums, key=lambda x: tuple(reversed(list(map(int, x.split("/"))))))

x.split("/") 获取每个值并生成一个字符串列表:

["235", "40", "17"]

使用 map(int, ...) 给出一个整数列表:

[235, 40, 17]

reversed() 扭转了局面:

[17, 40, 235]

tuple() 将其转换为元组:

(17, 40, 235)

与其他类似的元组相比,它给出了您想要的排序顺序。

关于python - 如何在python中对轮胎尺寸进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14050840/

相关文章:

c++ - 删除包含动态指针的 STL::list<class something> 类

string - 你怎么能在低级别对字符串单词进行排序?

python - 获取数据帧的协方差返回

python - 如何使用 flask_restplus 显示模式示例?

python - 使用 web python 下载不同语言的网页

python - 如果需要两次,只在列表理解中执行一次函数调用

css - 如何对齐CSS中水平ul菜单中所有选项卡的高度

python - 列表到字典 :there are duplicate elements which will act as keys but I want to collect values against same key and convert it into list value

javascript - 根据 1 个特定值的标识将对象拆分为多个有序数组

linux - 按列和一般编号对床文件进行排序