python 数字大小排序_python list字符按数字大小排序
python list字符按數字大小排序
在把list寫到csv過程中,遇到一個list的排序問題,list中存放的是數字字符,需要按數字大小來排序
測試源碼
testList = ['1', '5', '2', '10', '50', '21', '31', '3', '7']
print('testList={}'.format(testList))
normalSortList = testList[:]
normalSortList.sort()
print('after sort(): {}'.format(normalSortList))
intSortList = testList[:]
intSortList.sort(key = int)
print('after sort(key=int): {}'.format(intSortList))
運行
python3 ./test.py
testList=[‘1’, ‘5’, ‘2’, ‘10’, ‘50’, ‘21’, ‘31’, ‘3’, ‘7’]
after sort(): [‘1’, ‘10’, ‘2’, ‘21’, ‘3’, ‘31’, ‘5’, ‘50’, ‘7’] #會發現這里2在10之后,顯然不是自己需要的
after sort(key=int): [‘1’, ‘2’, ‘3’, ‘5’, ‘7’, ‘10’, ‘21’, ‘31’, ‘50’] #使用sort(key=int)來排序,結果就對了
作者:帥得不敢出門
總結
以上是生活随笔為你收集整理的python 数字大小排序_python list字符按数字大小排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 桥接模式_《JAVA与模式》之
- 下一篇: java例7_在Java 7中处理周数