![](/img/trans.png)
[英]Is there a way to convert a list of strings to a list of ints in python?
[英]Convert a list of strings to ints where possible
我在这里看到了各种各样的答案,但没有一个能完全回答我的问题。 我正在尝试转换以下列表
list = ['A', '2', '8', 'B', '3']
到以下内容:
list = ['A', 2, 8, 'B', 3]
我想将字符串保留为字符串,但在可能的情况下将字符串转换为整数。
我知道我可以做类似的事情:
list = [int(i) for i in list]
如果只是数字,但是我不确定如何将其混合使用。
总是try
/ except
:
oldlist = ['A', '2', '8', 'B', '3']
newlist = []
for x in oldlist:
try:
newlist.append(int(x))
except ValueError:
newlist.append(x)
newlist
# ['A', 2, 8, 'B', 3]
您可以使用str.isdigit()
:
>>> l = ['A', '2', '8', 'B', '3']
>>> [int(x) if x.isdigit() else x for x in l]
['A', 2, 8, 'B', 3]
考虑负数:
>>> l = ['A', '2', '8', 'B', '-3']
>>> [int(x) if x.isdigit() or x.startswith('-') and x[1:].isdigit() else x for x in l]
>>> ['A', 2, 8, 'B', -3]
我只是将转换提取为一个函数。
def int_if_possible(value):
try:
return int(value)
except (ValueError, TypeError):
return value
int_list = [int_if_possible(i) for i in int_list]
另外,我将您的列表重命名为int_list,这样,如果需要,我们仍然可以使用列表构造函数。
您可以使用try,除了block
lst1 = ['A', '2', '8', 'B', '3']
lst2 = []
for i in lst1:
try:
lst2.append(int(i))
except ValueError:
lst2.append(i)
print lst2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.