我有以下列表:
a = ['1', '2', 'hello']
我想获得
a = [1, 2, 'hello']
我的意思是,转换所有可能的整数。
这是我的功能:
def listToInt(l):
casted = []
for e in l:
try:
casted.append(int(e))
except:
casted.append(e)
return casted
但是,我可以使用map()
函数或类似的东西吗?
答案 0 :(得分:3)
当然,您可以使用map
def func(i):
try:
i = int(i)
except:
pass
return i
a = ['1', '2', 'hello']
print(list(map(func, a)))
答案 1 :(得分:2)
a = ['1', '2', 'hello']
y = [int(x) if x.isdigit() else x for x in a]
>> [1, 2, 'hello']
>> #tested in Python 3.5
也许是这样的?