Python3学习(十四):将列表中的元素转化为数字并排序

本文实例讲述了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)

猜你喜欢

转载自blog.csdn.net/liao392781/article/details/80592761