新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么將字符串轉(zhuǎn)換為數(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;
有沒有更簡單的語句可以做到呢?
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)
python學(xué)習(xí)網(wǎng),免費(fèi)的在線學(xué)習(xí)python平臺(tái),歡迎關(guān)注!
網(wǎng)站標(biāo)題:創(chuàng)新互聯(lián)Python教程:python怎么將字符串轉(zhuǎn)換為數(shù)字
本文鏈接:http://www.dlmjj.cn/article/djjdece.html


咨詢
建站咨詢
