简体   繁体   中英

Removing quotes from elements in python list

I have a python list that looks like alist = ['4', '1.6', 'na', '2e-6', '42'] . If i want to remove the quotes from this and make it look like [4, 1.6, na, 2e-6, 42] , normally i use the following code :

alist = [float(x) if type(x) is str else None for x in alist]

But this time, as I have the string 'na' as one of the elements in the list, this line of code will not work. Is there an elegant way to do this in python?

Assuming you are happy to replace the value 'na' with None , or more generally, any non-float looking text with None , then you could do something like:

def converter(x):
    try:
        return float(x)
    except ValueError:
        return None

alist = [converter(x) for x in alist]

This will convert anything to float that it can. So, as it stands, this will also convert existing numbers to float:

>>> [converter(x) for x in ('1.1', 2, 'na')]
[1.1, 2.0, None]

When python lists, sets, dicts, etc are printed out, they are printed in the same format that python uses to compile the "raw code." Python compiles lists in quotes. So you just need to iterate over the list.

Simply use a generator expression to fix this (though it really doens't have much effect unless you are displaying on a tkinter widget or something):

>>> alist = ['4', '1.6', 'na', '2e-6', '42']    

>>> for a in alist:
...    print(a)

>>> 4
>>> 1.6
>>> na
>>> 2e-6
>>> 42

I'm not sure where the "na", "nan" confusion is coming from. Regardless, if you want to lose the quotes, run your code through a generator expression and it will no longer be under the "list class" - hence, the quotes will no longer appear.

The list elements are all still the same type,

edit: clarity, grammar

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