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)
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With