Home > Backend Development > Python Tutorial > Python中列表元素转为数字的方法分析

Python中列表元素转为数字的方法分析

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-16 08:47:53
Original
2050 people have browsed it

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

有一个数字字符的列表:

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

Copy after login

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

numbers = [1, 5, 10, 8]

Copy after login

用一个循环来解决:

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

Copy after login

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

1.

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

Copy after login

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

numbers = map(int, numbers)

Copy after login

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

numbers = list(map(int, numbers))

Copy after login

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

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

Copy after login

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template