Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4469270
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: Python/Ruby

2019-08-02 20:48:06

在把list写到csv过程中,遇到一个list的排序问题,list中存放的是数字字符,需要按数字大小来排序
测试源码

点击(此处)折叠或打开

  1. testList = ['1', '5', '2', '10', '50', '21', '31', '3', '7']
  2. print('testList={}'.format(testList))
  3.                                                                                                                                                                                              
  4. normalSortList = testList[:]
  5. normalSortList.sort()
  6. print('after sort(): {}'.format(normalSortList))

  7. intSortList = testList[:]
  8. intSortList.sort(key = int)
  9. 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)来排序,结果就对了

作者:帅得不敢出门

阅读(281330) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~