简体   繁体   中英

if else in list comprehension with for loop

I've written my own simple solution for flatten list:

lists = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
new = []
for item in lists:
    if str(item).isdigit() != True:
        for v in item:
            new.append(v)
    else:
        new.append(item)
print(new)

But I want to add an else / elif to the following code to make code shorter:

new = [v for item in lists if str(item).isdigit() != True for v in item]

I don't know how to rather getting syntax errors.

Try this:

>>> [v for item in lists for v in (item if isinstance(item, list) else [item])]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]

This is slightly inefficient as it wraps an integer into a list, then iterates it, but it shouldn't matter for most purposes. Try not to use string representations for checking data types as you may end up with unexpected results (try running your original code with a float instead of an integer in the list for example).

First some notes for your original code:

  1. Instead of

    if str(item).isdigit():= True:

    use more Pythonic

     if not str(item).isdigit():
  2. Instead of the same, speculative way to reach your goal, use more clear

    if type(item) is not list:

Now, about else in list comprehension. It may be only in the first part of it, syntax of list comprehension don't allow it after the for clause (in if filtering expressions).

So you need to change the iterable in the second for of your list comprehension to always be an iterable, ie for example for item

  • [20, 30] it is OK (because it is an iterable)
  • 10 it is not OK (because it is not an iterable) - so let's put bracket around it - [10]

So we will switch between item and [item] depending of type(item) :

 item     if type(item) is list     else     [item]

(It is a conditional expression , not a list comprehension, so else is OK here.)

So the full solution may be

new = [v for item in lists 
         for v in (item if type(item) is list else [item])]

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