[英]list of string to int conversion
I want to convert a list
of python elements from str
to int
. 我想将python元素
list
从str
转换为int
。
My initial list looks like this: 我的初始列表如下所示:
l1 = ['723', '124', '1,211', '356']
The code I tried: 我试过的代码:
l1 = list(map(int, l1))
Resulted in an error that tells me: 导致出现一个错误,告诉我:
ValueError: invalid literal for int() with base 10: '1,211'
Alternatively, I tried map
ing with float
: 另外,我尝试使用
float
map
:
l1 = list(map(float, l1))
but, this also resulted in an error: 但是,这也会导致错误:
ValueError: could not convert string to float: '1,211'
I have tried both int
and float
in the code using map function. 我已经尝试使用map函数在代码中同时使用
int
和float
。 Can anyone correct me on where I'm going wrong. 谁能纠正我在哪里出错了。
Mapping either int
or float
to a value containing ','
will fail as converting str
s to floats or ints has the requirement that they represent correctly formed numbers (Python doesn't allow ','
as separators for floats or for thousands, it conflicts with tuples) 将
int
或float
映射到包含','
的值将失败,因为将str
转换为float或int要求它们代表正确格式的数字(Python不允许使用','
作为float 或数千的分隔符,这会发生冲突与元组)
If ','
is a thousands separator, use replace(',', '')
(as @tobias_k noted) in the comprehension you supply to map
and apply the int
immediately: 如果
','
是一个千位分隔符,请在提供的理解中使用replace(',', '')
(如@tobias_k所示)以立即map
并应用int
:
r = list(map(int , (i.replace(',', '') for i in l1)))
to get a wanted result for r
of: 获得以下的
r
的通缉结果:
[723, 124, 1211, 356]
Do it with a simple list comprehension. 通过简单的列表理解即可做到。
>>> l1 = ['723', '124', '1,211', '356']
>>> [int(i.replace(',','')) for i in l1]
[723, 124, 1211, 356]
This might help: 这可能会有所帮助:
l1 = ['723', '124', '1,211', '356']
l1 = [int(i.replace(',','')) for i in l1]
for x in l1:
print("{:,}".format(x))
Output: 输出:
723
124
1,211
356
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.