sum*_*000 7 python string int list
在Python中,我想转换一个字符串列表:
l = ['sam','1','dad','21']
Run Code Online (Sandbox Code Playgroud)
并将整数转换为整数类型,如下所示:
t = ['sam',1,'dad',21]
Run Code Online (Sandbox Code Playgroud)
我试过了:
t = [map(int, x) for x in l]
Run Code Online (Sandbox Code Playgroud)
但是显示错误.
如何将列表中的所有intable字符串转换为int,将其他元素保留为字符串?
我的清单可能是多维的.适用于通用列表的方法更可取:
l=[['aa','2'],['bb','3']]
我使用自定义功能:
def try_int(x):
try:
return int(x)
except ValueError:
return x
Run Code Online (Sandbox Code Playgroud)
例:
>>> [try_int(x) for x in ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]
Run Code Online (Sandbox Code Playgroud)
编辑:如果您需要将上述内容应用于列表列表,为什么在构建嵌套列表时没有将这些字符串转换为int?
无论如何,如果你需要,只需要选择如何迭代这样的嵌套列表并应用上面的方法.
这样做的一种方法可能是:
>>> list_of_lists = [['aa', '2'], ['bb', '3']]
>>> [[try_int(x) for x in lst] for lst in list_of_lists]
[['aa', 2], ['bb', 3]]
Run Code Online (Sandbox Code Playgroud)
您可以明确地将其重新分配给list_of_lists
:
>>> list_of_lists = [[try_int(x) for x in lst] for lst in list_of_lists]
Run Code Online (Sandbox Code Playgroud)