Pergunta

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']
Foi útil?

Solução

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
>>>

Outras dicas

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]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top