문제

I want to convert a str into an int in a list. Example:

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

I want just the first element x[0] to switch to an int:

x = [1, '24', 'M', 'technician', '85711']
도움이 되었습니까?

해결책

Just assign to an index of the list:

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

This solution keeps the list object the same too:

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

다른 팁

If you wish to convert just all digits to int in a mixed list , try it:

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

output:

[1, 24, 'M', 'technician', 85711]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top