How to convert strings numbers to integers in a list?

后端 未结 4 1630
[愿得一人]
[愿得一人] 2020-12-05 08:24

I have a list say:

[\'batting average\', \'306\', \'ERA\', \'1710\']

How can I convert the intended numbers without touching the strings?

相关标签:
4条回答
  • 2020-12-05 08:48

    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])
    
    0 讨论(0)
  • 2020-12-05 08:51
    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)

    0 讨论(0)
  • 2020-12-05 09:09

    Try this:

    def convert( someList ):
        for item in someList:
            try:
                yield int(item)
            except ValueError:
                yield item
    
    newList= list( convert( oldList ) )
    
    0 讨论(0)
  • 2020-12-05 09:13
    changed_list = [int(f) if f.isdigit() else f for f in original_list]
    
    0 讨论(0)
提交回复
热议问题