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

yipeiwu_com6年前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设计】。

相关文章

python之array赋值技巧分享

首先上一段程序: import numpy as np list_a = list(range(10)) print("list_a: {}".format(list_a)) a...

Python cookbook(数据结构与算法)对切片命名清除索引的方法

本文实例讲述了Python对切片命名清除索引的方法。分享给大家供大家参考,具体如下: 问题:如何清理掉到处都是硬编码的切片索引 解决方案:对切片命名 假设有一些代码用来从字符串的固定位置...

python实现在pickling的时候压缩的方法

本文实例讲述了python实现在pickling的时候压缩的方法。分享给大家供大家参考。 具体方法如下: import cPickle,gzip def save(filename,...

python tkinter基本属性详解

python tkinter基本属性详解

1.外形尺寸 尺寸单位:只用默认的像素或者其他字符类的值!,不要用英寸毫米之类的内容。 btn = tkinter.Button(root,text = '按钮') # 设置按钮尺寸...

pytorch forward两个参数实例

以channel Attention Block为例子 class CAB(nn.Module): def __init__(self, in_channels, out_c...