简体   繁体   English

将列表中的数字字符串转换为数字(整数/浮点)类型

[英]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]

This is one way of doing that by checking if the str isnumeric and type cast to int if it is a numeric value.这是通过检查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)

I think you can use try-except:我认为您可以使用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

More info about try-except here有关 try-except 的更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM