Unpack a list from a single list

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

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 subquery, which, it seems to me, I need to unpack somehow with a lot of lines of code, but I would prefer not to do this if I could just fix the list. My goal would be to read the first "line"

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

... and the rest of the output matches this example. My attempts

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'm new to listing understanding. I appreciate any input and guidance. Thank you in advance for your time.

+4
2

. python.

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

mylist[x] . , "" , , python 3.5 .

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

x , mylist[x] .

+4

, :

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

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

 x         -> 11
 mylist[x] -> ['TypeB', 'Kline', '', '', 'Category']

, x .

+4

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


All Articles