[英]How do I convert a list of strings in a list composed of ints and floats to both ints and floats?
例如,我有列表 ['-1','9','7.8'] 如何将列表转换为 [-1,9,7.8] 而不必在全部转换为浮点数或全部转换为浮点数之间进行选择整数?
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 ]
Here 2 simple solutions这里有2个简单的解决方案
# 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.
但是,如果您真的需要区分 2,那么只需检查是否加点。
**Solution 3 ** **解决方案 3 **
"Ask forgiveness not permission" just try to convert it to a int, if it fails then to a float “请求宽恕而不是许可”只是尝试将其转换为 int,如果失败则为浮点数
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]
int(x) if int(x) == float(x) else float(x)
是确定字符串是整数还是浮点数的有用方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.