手机
当前位置:查字典教程网 >脚本专栏 >python >Python中列表元素转为数字的方法分析
Python中列表元素转为数字的方法分析
摘要:本文实例讲述了Python中列表元素转为数字的方法。分享给大家供大家参考,具体如下:有一个数字字符的列表:numbers=['1','5',...

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

有一个数字字符的列表:

numbers = ['1', '5', '10', '8']

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

numbers = [1, 5, 10, 8]

用一个循环来解决:

new_numbers = []; for n in numbers: new_numbers.append(int(n)); numbers = new_numbers;

有没有更简单的语句可以做到呢?

1.

numbers = [ int(x) for x in numbers ]

2. Python2.x,可以使用map函数

numbers = map(int, numbers)

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

numbers = list(map(int, numbers))

3.还有一种比较复杂点:

for i, v in enumerate(numbers): numbers[i] = int(v)

希望本文所述对大家Python程序设计有所帮助。

【Python中列表元素转为数字的方法分析】相关文章:

python中定义结构体的方法

Python中关键字is与==的区别简述

Python中的yield浅析

python每次处理固定个数的字符的方法总结

python操作MySQL数据库的方法分享

python中的列表推导浅析

Python操作列表的常用方法分享

python生成器的使用方法

Python中os和shutil模块实用方法集锦

python迭代器的使用方法实例

精品推荐
分类导航