本文介紹了列表列表,將所有字符串轉換為 int,Python 3的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試將大列表中小列表的所有元素轉換為整數,所以它應該如下所示:
I am trying to convert all elements of the small lists in the big list to integers, so it should look like this:
current list:
list = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]
for e in list:
for i in e:
i = int(i)
new list:
list = [[1,2,3],[8,6,8],[2,9,3],[2,5,7],[5,4,1],[0,8,7]]
誰能告訴我為什么這不起作用并向我展示一種有效的方法?謝謝!
Could anyone tell me why doesn't this work and show me a method that does work? Thanks!
推薦答案
你可以使用嵌套列表推導:
You can use a nested list comprehension:
converted = [[int(num) for num in sub] for sub in lst]
我也將list
重命名為lst
,因為list
是列表類型的名稱,不推薦用于變量名.
I also renamed list
to lst
, because list
is the name of the list type and not recommended to use for variable names.
這篇關于列表列表,將所有字符串轉換為 int,Python 3的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!