python列表字符串转数字_python 将列表中的字符串转为数字
生活随笔
收集整理的這篇文章主要介紹了
python列表字符串转数字_python 将列表中的字符串转为数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文實例講述了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)
轉:https://www.jb51.net/article/86561.htm
原文地址:https://www.cnblogs.com/sea-stream/p/9484024.html
總結
以上是生活随笔為你收集整理的python列表字符串转数字_python 将列表中的字符串转为数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: canvas换图时候会闪烁_Canvas
- 下一篇: 北京环球影城速通卡怎么买