簡體   English   中英

字符串到int轉換的列表

[英]list of string to int conversion

我想將python元素liststr轉換為int

我的初始列表如下所示:

l1 = ['723', '124', '1,211', '356']

我試過的代碼:

l1 =  list(map(int, l1))

導致出現一個錯誤,告訴我:

ValueError: invalid literal for int() with base 10: '1,211'

另外,我嘗試使用float map

l1 =  list(map(float, l1))

但是,這也會導致錯誤:

ValueError: could not convert string to float: '1,211'

我已經嘗試使用map函數在代碼中同時使用intfloat 誰能糾正我在哪里出錯了。

intfloat映射到包含','的值將失敗,因為將str轉換為float或int要求它們代表正確格式的數字(Python不允許使用','作為float 數千的分隔符,這會發生沖突與元組)

如果','是一個千位分隔符,請在提供的理解中使用replace(',', '') (如@tobias_k所示)以立即map並應用int

r = list(map(int , (i.replace(',', '') for i in l1)))

獲得以下的r的通緝結果:

[723, 124, 1211, 356]

通過簡單的列表理解即可做到。

>>> l1 = ['723', '124', '1,211', '356']
>>> [int(i.replace(',','')) for i in l1]
[723, 124, 1211, 356]

這可能會有所幫助:

l1 = ['723', '124', '1,211', '356']
l1 = [int(i.replace(',','')) for i in l1]
for x in l1:
    print("{:,}".format(x))

輸出:

723
124
1,211
356

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM