简体   繁体   English

如何将字符串数转换为列表中的整数?

[英]How to convert strings numbers to integers in a list?

I have a list say: 我有一个清单说:

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

How can I convert the intended numbers without touching the strings? 如何在不触及字符串的情况下转换预期的数字?

Thank you for the help. 感谢您的帮助。

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

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) 如果你的列表包含float,string和int(在评论中由@d.putto指出)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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