How to convert strings numbers to integers in a list?

佐手、 提交于 2019-11-27 19:52:47
Alex Martelli
changed_list = [int(f) if f.isdigit() else f for f in original_list]

The data looks like you would know in which positions the numbers are supposed to be. In this case it's probably better to explicitly convert the data at these positions instead of just converting anything that looks like a number:

ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
S.Lott

Try this:

def convert( someList ):
    for item in someList:
        try:
            yield int(item)
        except ValueError:
            yield item

newList= list( convert( oldList ) )
a= ['batting average', '306', 'ERA', '1710.5']

[f if sum([c.isalpha() for c in f]) else float(f) for f in a ]

if your list contains float, string and int (as pointed about by @d.putto in the comment)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!