Use a conditional inside a list comprehension
>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]
Interesting edge case of exponentials. You can add onto the conditional.
>>> s = ['1', '2', '3.4', '5.6', '7.8' , '1e2']
>>> [float(i) if '.' in i or 'e' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
Using isdigit
is the best as it takes care of all the edge cases (mentioned by Steven in a comment)
>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [int(i) if i.isdigit() else float(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…