Reputation: 191
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.
Upvotes: 3
Views: 1338
Reputation: 14141
First some notes for your original code:
Instead of
if str(item).isdigit() != True:
use more Pythonic
if not str(item).isdigit():
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, i.e. 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])]
Upvotes: 1
Reputation: 59184
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).
Upvotes: 7