1. 程式人生 > >python 將列表中的字符串轉為數字

python 將列表中的字符串轉為數字

轉換 字符串 www. one rate 如果 .net 語句 new

本文實例講述了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

python 將列表中的字符串轉為數字