简体   繁体   English

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

[英]Converting one string to a int in a list

I want to convert a str into an int in a list. 我想将str转换为列表中的int。 Example: 例:

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

I want just the first element x[0] to switch to an int: 我只希望第一个元素x[0]切换为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: 如果您希望仅将所有数字转换为混合列表中的int,请尝试:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM