将一个字符串转换为列表中的int

时间:2014-04-21 18:05:56

标签: python list type-conversion

我想将str转换为列表中的int。例如:

x = ['1', '24', 'M', 'technician', '85711']

我只希望第一个元素x[0]切换到int:

x = [1, '24', 'M', 'technician', '85711']

2 个答案:

答案 0 :(得分:3)

只需分配到列表的索引:

>>> x = ['1', '24', 'M', 'technician', '85711']
>>> x[0] = int(x[0])
>>> x
[1, '24', 'M', 'technician', '85711']
>>>

此解决方案也使列表对象保持相同:

>>> x = ['1', '24', 'M', 'technician', '85711']
>>> id(x)
35174000
>>> x[0] = int(x[0])
>>> id(x)
35174000
>>>

答案 1 :(得分:0)

如果您希望将所有数字转换为混合列表中的int,请尝试:

a = ['1', '24', 'M', 'technician', '85711']
b = map(lambda x: int(x) if str(x).isdigit() else x,a)
print b

输出:

[1, 24, 'M', 'technician', 85711]