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


有一个数字字符的列表:

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

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

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

用一个循环来解决:

1
2
3
4
new_numbers = [];
for n in numbers:
   new_numbers.append( int (n));
numbers = new_numbers;

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

1.

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

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

1
numbers = map ( int , numbers)

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

1
numbers = list ( map ( int , numbers))

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM