简体   繁体   中英

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?

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"). There are just too many things that can go wrong with a conversion, and it's hard to check them all in advance.

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:

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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