1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python 数字大小排序_python list字符按数字大小排序

python 数字大小排序_python list字符按数字大小排序

时间:2021-05-04 05:09:23

相关推荐

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)来排序,结果就对了

作者:帅得不敢出门

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。