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?
CodePudding user response:
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]
CodePudding user response:
You can use list comprehension and ternary operator to do this
lst =['-1','9','7.8']
lst = [int(numStr) if '.' in numStr else float(numStr) for numStr in lst ]
CodePudding user response:
int(x) if int(x) == float(x) else float(x)
is a useful way of deciding if a string is integer or float