如何将intable字符串列表转换为int [英] How to convert list of intable strings to int
问题描述
在Python中,我想转换一个字符串列表:
In Python, I want to convert a list of strings:
l = ['sam','1','dad','21']
并将整数转换为整数类型,如下所示:
and convert the integers to integer types like this:
t = ['sam',1,'dad',21]
我试过:
t = [map(int, x) for x in l]
但显示错误。
如何将列表中的所有 intable 字符串转换为int,将其他元素保留为字符串?
How could I convert all intable strings in a list to int, leaving other elements as strings?
我的列表可能是多维的。适用于通用列表的方法更可取:
My list might be multi-dimensional. A method which works for a generic list would be preferable:
l = [['aa','2'],['bb' ,'3']]
推荐答案
我使用自定义函数:
def try_int(x):
try:
return int(x)
except ValueError:
return x
示例:
>>> [try_int(x) for x in ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]
编辑如果您需要将以上内容应用于列表列表,为什么在构建嵌套列表时没有将这些字符串转换为int?
If you need to apply the above to a list of lists, why didn't you converted those strings to int while building the nested list?
无论如何,如果需要,如何迭代这样的嵌套列表并应用上述方法只是一个选择问题。
Anyway, if you need to, it's just a matter of choice on how to iterate over such nested list and apply the method above.
这样做的一种方法可能是:
One way for doing that, might be:
>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]
您可以明确地将其重新分配给 list_of_lists
:
You can obviusly reassign that to list_of_lists
:
>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]
这篇关于如何将intable字符串列表转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!