Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack list from single line list comprehension

Python beginner here. I have a list of lists that I am trying to filter based on the value in mylist[x][0], plus add an index value to each resulting sublist. Given the following list comrehension:

shortlist = [[x, mylist[x]] for x in range(1,20) if mylist[x][0] == 'TypeB']

I get the following output:

[[11, ['TypeB', 'Kline', '', '', 'Category']],
 [12, ['TypeB', '', '[Aa]bc', '', 'Category3']],
 [13, ['TypeB', '', '[Z]bc', '', 'Category']],
 [14, ['TypeB', '', 'Kline', '[Aa]bc', 'Category4']],
 [15, ['TypeB', '', '', '[Z]bc', 'Category']],
 [16, ['TypeB', '', '', 'Kline', 'Category5']],
 [17, ['TypeB', '[Aa]bc', '', '', 'Category']],
 [18, ['TypeB', '[Z]bc', '', '', 'Category2']],
 [19, ['TypeB', 'Kline', '', '', 'Category']]]

This creates a sub-sublist that I guess I need to unpack somehow with more lines of code, but I'd rather not do that if I can just correct the list comprehension. My goal would be to have the first "line" read

[[11, 'TypeB', 'Kline', '', '', 'Category'],

...and the rest of the output follow suit. My attempts at

shortlist = [x, mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

and

shortlist = [x for x in range(1,20) if mylist[x][0] == 'TypeB', mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

both give syntax errors. Obviously I am new to list comprehensions. I value any input and guidance. Thank you in advance for your time.

like image 831
GJury Avatar asked Jan 28 '23 23:01

GJury


1 Answers

You need to concatenate your inner lists together. A few ways to do this depending on the version of python you're using.

shortlist = [[x, *mylist[x]] for x in range(1,20) if mylist[x][0] == 'TypeB']

Will unpack all the values of mylist[x] into the list. Probably the most "pythonic" way, however will only work from python 3.5 up.

shortlist = [[x] + mylist[x] for x in range(1,20) if mylist[x][0] == 'TypeB']

Will create a list with just x in it, and then add mylist[x] onto the end.

like image 109
SCB Avatar answered Feb 16 '23 00:02

SCB