如何将字符串数转换为列表中的整数?
题
我有一个清单说:
['batting average', '306', 'ERA', '1710']
如何在不触及字符串的情况下转换目标数字?
感谢您的帮助。
解决方案
changed_list = [int(f) if f.isdigit() else f for f in original_list]
其他提示
数据看起来就像你知道数字应该在哪个位置。在这种情况下,最好显式转换这些位置的数据,而不是只转换看起来像数字的任何东西:
ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
试试这个:
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 ]
如果你的列表包含float,string和int(在评论中由@d.putto指出)
不隶属于 StackOverflow