python列表字符串转数字_python 将列表中的字符串转为数字
本文實(shí)例講述了Python中列表元素轉(zhuǎn)為數(shù)字的方法。分享給大家供大家參考,具體如下:
有一個(gè)數(shù)字字符的列表:
numbers = [‘1‘, ‘5‘, ‘10‘, ‘8‘]
想要把每個(gè)元素轉(zhuǎn)換為數(shù)字:
numbers = [1, 5, 10, 8]
用一個(gè)循環(huán)來解決:
new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numbers = new_numbers;
有沒有更簡(jiǎn)單的語句可以做到呢?
1.
numbers = [ int(x) for x in numbers ]
2. Python2.x,可以使用map函數(shù)
numbers = map(int, numbers)
如果是3.x,map返回的是map對(duì)象,當(dāng)然也可以轉(zhuǎn)換為List:
numbers = list(map(int, numbers))
3.還有一種比較復(fù)雜點(diǎn):
for i, v in enumerate(numbers): numbers[i] = int(v)
轉(zhuǎn):https://www.jb51.net/article/86561.htm
原文地址:https://www.cnblogs.com/sea-stream/p/9484024.html
總結(jié)
以上是生活随笔為你收集整理的python列表字符串转数字_python 将列表中的字符串转为数字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: canvas换图时候会闪烁_Canvas
- 下一篇: python 可执行文件_如何通过Pyt