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

作者:帅得不敢出门

  • 13
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值