本文實例講述了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)
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
本文標題: Python中列表元素轉為數字的方法分析
本文地址: http://www.cppcns.com/jiaoben/python/153385.html