简体   繁体   中英

nested list comprehension with if/else statement

I have the impression this snippet can be improved with list comprehension and a function based on the answers related. Then, I proceeded to changed this snippet:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
flat_list = []
for sublist in l:
    print("sublist: ", sublist)
    for item in sublist:
        if type(item)== list:
            for i in item:
                flat_list.append(i)
        else:
            flat_list.append(item)

print(flat_list)

To this new version which is not working:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]

def foo(item):
    flat_l=[]
    if type(item)== list:
        for i in item:
            flat_l.append(i)
    else:
        flat_l.append(item)

    return flat_l

flat_list=[item for sublist in l foo(item) for item in sublist]

print(flat_list)

Which is complaining due to syntax error:

File "", line 33 flat_list=[item for sublist in l foo(item) for item in sublist] ^ SyntaxError: invalid syntax

my code in python3

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
e=[]
any(e.extend(i[0]) if isinstance(i[0], list) else e.extend(i) for i in l)
print(e)

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