將 Python 中的數字字串列表轉換為整數列表
對於使用 Python 進行資料處理,我們可能會遇到一個場景,其中一個列表中包含數字的字串。為了能夠進行計算,我們需要將字串轉換為數字。在本文中,我們將看到如何在列表中將字串更改為數字。
使用 int
int 函式可應用於列表的字串元素,並將其轉換為整數。我們必須仔細設計 for 迴圈以遍歷每個元素並獲得結果,即使單個元素中有多個字串。
示例
listA = [['29','12'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use int
res = [[int(n) for n in element] for i in listA for element in i]
# Result
print("The numeric lists: ",res)輸出
執行以上程式碼,會給我們以下結果 -
Given list A: [['29', '12'], ['25'], ['70']] The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]
使用 map
我們還可以使用對映函式,它能夠將給定的函式反覆應用於提供給該函式的每個引數。我們建立一個讀取列表中每個內部列表中的元素的迴圈。如果內部列表包含多個元素,則此方法不起作用。
示例
listA = [['29'], ['25'], ['70']]
# Given lists
print("Given list A: ", listA)
# Use map
res = [list(map(int, list(elem[0]))) for elem in listA if elem ]
# Result
print("The numeric lists: ",res)輸出
執行以上程式碼,會給我們以下結果 -
Given list A: [['29'], ['25'], ['70']] The numeric lists: [[2, 9], [2, 5], [7, 0]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP