简体   繁体   中英

Separating mixed float/string in same element in python list

I have a list like this

A = [14, 15.2, '22.6g', '27.28g', '10g', '15.2R', '12.4k']

I would like to split list A it into two lists like

B = [14, 15.2, 22.6, 27.28, 10, 15.2, 12.4]

C = ['NA', 'NA', 'g', 'g', 'g', 'R', 'k']

I'm not sure how to accomplish this without some sort of delimitator between the numbers and letters.

Assuming the unit is always one character long, you could use a list comprehension like:

B, C = map(list, zip(*[[float(x[:-1]), x[-1]] if isinstance(x, str) else [x, 'NA'] for x in A]))

Output:

[14, 15.2, 22.6, 27.28, 10.0, 15.2, 12.4]    

['NA', 'NA', 'g', 'g', 'g', 'R', 'k']

If units are more than 1 character long, we could use a splitter function:

def splitter(x):
    num, unit = '', ''
    for i in x:
        if i.isdigit() or i=='.':
            num += i
        else:
            unit += i
    return [float(num), unit]

B, C = map(list, zip(*[splitter(x) if isinstance(x, str) else [x, 'NA'] for x in A]))

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