Unexpected withdrawal from list comprehension

I have a list of input as follows:

test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl']

which I need to smooth out, so get rid of the tuple and list as the corresponding second and third elements test_list

Expected Result:

['a', 'abc', 'd', 'efgh', 'i', 'jkl']

I have a problem finding the correct list comprehension. I tried the following 2 examples:

result = [xs if type(xs) is str else x for xs in test_list for x in xs]
print('result', result) 
# this outputs:
# ['a', 'abc', 'd', 'efgh', 'i', 'jkl', 'jkl', 'jkl']

result = [x if ((type(xs) is list) or (type(xs) is tuple)) else xs for xs in test_list for x in xs]
print('result',result)
#this also outputs:
# ['a', 'abc', 'd', 'efgh', 'i', 'jkl', 'jkl', 'jkl']  

as you can see, it β€œsmoothes” the list, but repeats the last item based on the number of characters in the last item. Example, if the last element test_listis equal 'jklm', then the resultlast element is repeated 4 times.

I would like to know if there is a list comprehension that aligns the input list to the expected result without repeating the last element.

+4
source share
3

:

[x for sub in test_list for x in (sub if isinstance(sub, (list, tuple)) else [sub])]

isinstance, type(...) . - , .

+7

:

test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl']
result = [x for xs in test_list for x in (xs if isinstance(xs, (tuple, list)) else [xs])]

, for

+4

You can always convert all the individual elements test_listinto lists:

>>> test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl']
>>> convert_to_lists = [[x] if not isinstance(x, (list, tuple)) else x for x in test_list]
>>> convert_to_lists
[['a'], ('abc', 'd'), ['efgh', 'i'], ['jkl']]

Then just smooth it out with itertools.chain_from_iterable:

>>> from itertools import chain
>>> list(chain.from_iterable(convert_to_lists))
['a', 'abc', 'd', 'efgh', 'i', 'jkl']

or all in one line:

list(chain.from_iterable([x] if not isinstance(x, (list, tuple)) else x for x in test_list))
+2
source

Source: https://habr.com/ru/post/1691625/


All Articles