天天看點

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