Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension for if else statemets

Tags:

python

How to express by using list comprehension? Newbie needs help. Thanks a lot. code below:

lst = ['chen3gdu',2,['chengdu','suzhou']]
result = []
for elem in lst:
    if type(elem) == list:
        for num in elem:
            result.append(num)
    else:
        result.append(elem)
like image 250
running man Avatar asked Mar 16 '19 12:03

running man


1 Answers

This isn't that suitable for a list comprehension, but you can achieve it by special-casing when you don't have a list, wrapping such elements in a list for iteration:

result = [num for elem in lst for num in ([elem] if not isinstance(elem, list) else elem)]

which, written out to the same for you were using, plus an extra variable to call out the conditional expression I used, is the equivalent of:

result = []
for elem in lst:
    _nested = [elem] if not isinstance(elem, list) else elem
    for num in _nested:
        result.append(num)

You might want to encapsulate flattening the irregular structure, in a generator function:

def flatten(irregular_list):
    for elem in irregular_list:
        if isinstance(elem, list):
            yield from elem
        else:
            yield elem

and then use that in list comprehensions and such, with additional operations. For just flattening, passing the generator function to list() is cleaner, e.g. result = list(flatten(lst)).

like image 76
Martijn Pieters Avatar answered Oct 11 '22 02:10

Martijn Pieters