ITPub博客

首页 > 应用开发 > > python list字符按数字大小排序

python list字符按数字大小排序

作者:qingcai 时间:2019-08-19 16:10:59 0 删除 编辑

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2899/viewspace-3126887/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    71
  • 访问量
    681