將 Python 中列表中的所有字串轉換為整數
有時候,我們可能有一個包含字串的列表,但字串本身是數字和結束引號。在此類列表中,我們要將字串元素轉換為實際整數。
使用 int()
int 函式採用引數,並將其轉換為整數(如果這些引數已經是數字)。因此,我們設計一個 for 迴圈來遍歷列表中的每一個元素,並應用 in 函式。我們將最終結果儲存在一個新列表中。
示例
listA = ['5', '2','-43', '23'] # Given list print("Given list with strings : \n",listA) # using int res = [int(i) for i in listA] # Result print("The converted list with integers : \n",res)
輸出
執行以上程式碼會得到以下結果 −
Given list with strings : ['5', '2', '-43', '23'] The converted list with integers : [5, 2, -43, 23]
使用 map 和 list
map 函式可用於將 in 函式應用於給定列表中作為字串存在的每個元素。
示例
listA = ['5', '2','-43', '23'] # Given list print("Given list with strings : \n",listA) # using map and int res = list(map(int, listA)) # Result print("The converted list with integers : \n",res)
輸出
執行以上程式碼會得到以下結果 −
Given list with strings : ['5', '2', '-43', '23'] The converted list with integers : [5, 2, -43, 23]
廣告