For example, I have the list ['-1','9','7.8'] How do I convert the list to [-1,9,7.8] without having to choose between converting all to a float or all to an integer?
Asked
Active
Viewed 131 times
3 Answers
0
You can use list comprehension and ternary operator to do this
lst =['-1','9','7.8']
lst = [float(numStr) if '.' in numStr else int(numStr) for numStr in lst ]

carlosdafield
- 1,479
- 5
- 16
0
Here 2 simple solutions
# 1 Just convert to float.
print([float(i) for i in ['-1','9','7.8']])
# 2 Check if are dotted
convert = [float(i) if '.' in i else int(i) for i in ['-1','9','7.8']]
print(convert)
The first would work because a integer can be always converted to float. But if you really need to have the 2 differentiated then just check if are dotted.
**Solution 3 **
"Ask forgiveness not permission" just try to convert it to a int, if it fails then to a float
def int_float_converter(data):
converted_data = []
for d in data:
val = None
try:
val = int(d)
except ValueError:
val = float(d)
finally:
if val:
converted_data.append(val)
return converted_data
converted = int_float_converter(['-1','9','7.8'])
print(converted)
# [-1, 9, 7.8]

Federico Baù
- 6,013
- 5
- 30
- 38
-1
int(x) if int(x) == float(x) else float(x)
is a useful way of deciding if a string is integer or float

mkemaltas
- 154
- 3
-
2careful, pass something like int('7.8') will faile -> `ValueError: invalid literal for int() with base 10:` – Federico Baù Nov 09 '21 at 20:40