当前位置:主页 > 软件编程 > Python代码 >

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

时间:2021-04-01 08:18:17 | 栏目: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)

您可能感兴趣的文章:

相关文章