python 将列表中的字符串转为数字

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

有一个数字字符的列表:函数

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

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

numbers = [1, 5, 10, 8]

用一个循环来解决:code

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

有没有更简单的语句能够作到呢?htm

1.对象

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

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

numbers = map(int, numbers)

若是是3.x,map返回的是map对象,固然也能够转换为List:List

numbers = list(map(int, numbers))

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

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


转:https://www.jb51.net/article/86561.htm
相关文章
相关标签/搜索