[英]Convert numerical strings in a list to numerical (Integer/float) type
I have a list of mixed types of data:我有一个混合类型的数据列表:
list = ['Diff', '', '', 0, '+16.67%', '+2.81%', 0, '+13.33%']
I only want to convert the numerical strings in this list to Integers/float, so my list will be:我只想将此列表中的数字字符串转换为整数/浮点数,因此我的列表将是:
newlist = ['Diff', '', '', 0, +16.67%, +2.81%, 0, +13.33%]
I know this res = [eval(i) for i in list]
can convert all the strings to integers if everything in my list is numerical strings, but how do I do to only convert the numerical strings in a mixed-type list?我知道这个
res = [eval(i) for i in list]
如果我的列表中的所有内容都是数字字符串,则可以将所有字符串转换为整数,但我该怎么做才能只转换混合类型列表中的数字字符串?
When doing type conversions in python, you attempt a conversion first and provide a reasonable fallback for the case it fails ("ask forgiveness, not permission").在 python 中进行类型转换时,您首先尝试转换并为失败的情况提供合理的回退(“请求宽恕,而不是许可”)。 There are just too many things that can go wrong with a conversion, and it's hard to check them all in advance.
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])
To handle values like 12.34%
you can do something like:要处理
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.