当前位置:首页 » python教程 » 正文

Python将列表中的元素转化为数字并排序的示例

看: 1066次  时间:2020-12-29  分类 : python教程

本文实例讲述了Python中列表元素转为数字的方法。分享给大家供大家参考,具体如下:

有一个数字字符的列表:

numbers = ['2', '4', '1', '3']

想要把每个元素转换为数字:

numbers = [2, 4, 1, 3]

1. Python2.x,可以使用map函数:

numbers = map(int, numbers)

2. Python3.x,map返回的是map对象,当然也可以转换为List:

numbers = list(map(int, numbers))

排序:

使用sorted函数,从小到大排序:

numbers = sorted(numbers, reverse = False)

从大到小排序:

numbers = sorted(numbers, reverse = True)

以上这篇Python将列表中的元素转化为数字并排序的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!