Python中將字串列表轉換為排序後的整數列表
使用Python分析資料時,我們可能會遇到將數字表示為字串的情況。在本文中,我們將處理一個包含以字串形式存在的數字的列表,我們需要將其轉換為整數,然後以排序的方式表示它們。
使用map和sorted
在這種方法中,我們使用map函式將int函式應用於列表的每個元素。然後,我們將sorted函式應用於列表,該函式對數字進行排序。它也可以處理負數。
示例
listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Use mapp listint = map(int, listA) # Apply sort res = sorted(listint) # Result print("Sorted list of integers: \n",res)
輸出
執行上述程式碼將得到以下結果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
使用int和sort
在這種方法中,我們使用for迴圈應用int函式並將結果儲存到列表中。然後,將sort函式應用於列表。最終結果顯示排序後的列表。
示例
listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Convert to int res = [int(x) for x in listA] # Apply sort res.sort() # Result print("Sorted list of integers: \n",res)
輸出
執行上述程式碼將得到以下結果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
使用sorted和int
這種方法與上述方法類似,只是我們將int函式透過for迴圈應用,並將結果包含在sorted函式中。這是一個單一表達式,它給我們最終的結果。
示例
listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Convert to int res = sorted(int(x) for x in listA) # Result print("Sorted list of integers: \n",res)
輸出
執行上述程式碼將得到以下結果:
Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
廣告