[英]Convert numerical strings in a list to numerical (Integer/float) type
我有一个混合类型的数据列表:
list = ['Diff', '', '', 0, '+16.67%', '+2.81%', 0, '+13.33%']
我只想将此列表中的数字字符串转换为整数/浮点数,因此我的列表将是:
newlist = ['Diff', '', '', 0, +16.67%, +2.81%, 0, +13.33%]
我知道这个res = [eval(i) for i in list]
如果我的列表中的所有内容都是数字字符串,则可以将所有字符串转换为整数,但我该怎么做才能只转换混合类型列表中的数字字符串?
在 python 中进行类型转换时,您首先尝试转换并为失败的情况提供合理的回退(“请求宽恕,而不是许可”)。 go 转换错误的东西太多了,而且很难提前检查它们。
def maybe_int(x):
try:
return int(x)
except (TypeError, ValueError):
return x
lst = ['1', 'yes', 'diff', '43', '2', '4']
print([maybe_int(x) for x in lst])
要处理12.34%
之类的值,您可以执行以下操作:
def convert(x):
x = str(x)
if x.endswith('%'):
try:
return float(x[:-1])
except ValueError:
return x
try:
return float(x)
except ValueError:
return x
result = [convert(x) for x in your_list]
这是通过检查str是否为数字的一种方法,如果它是数字值,则类型转换为int 。
list = ['1', 'yes', 'diff', '43', '2', '4']
print(list)
for i, n in enumerate(list):
if n.isnumeric():
list[i] = int(n)
print(list)
我认为您可以使用try-except:
for i in range(len(array)):
try:
array[i] = int(array[i])
except:
print("Can not cast this element to int") # you can write nothing here
有关 try-except 的更多信息在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.