Ad

Lots Of Lists Of Lists - Return Only Lists That The First Index Matches

I have a websocket feed that return lists or lists of lists and I want to pull out only individual lists that meet the criteria that I want.

Example data:

[['o', 0, '9726.85438804', '0.40716427']]
[['o', 0, '9909.02930523', '0.00000000'], ['o', 0, '9855.53483394', '12.07669000']]
[['o', 0, '9669.50657753', '0.00000000'], ['o', 0, '9669.60657753', '0.30000000']]
[['o', 1, '9660.00000000', '0.00000000'], ['o', 1, '9658.52360670', '0.00000000'], ['o', 1, '9652.51635910', '0.00000000'], ['o', 1, '9652.50517986', '0.00244445'], ['t', '23068523', 0, '9660.00000000', '0.00191511', 1525594948], ['t', '23068524', 0, '9660.00000000', '0.00160000', 1525594948], ['t', '23068525', 0, '9658.52360670', '0.00020655', 1525594948], ['t', '23068526', 0, '9652.51635910', '0.00020668', 1525594948], ['t', '23068527', 0, '9652.50517986', '0.10115560', 1525594948]]
[['o', 0, '9727.41662891', '0.58301369']]
[['o', 1, '9642.52790569', '0.00000000'], ['o', 1, '9652.52790569', '0.40000000']]
[['o', 1, '9650.82850048', '0.00000000']]
[['o', 0, '9669.60657753', '0.29000000'], ['t', '23068528', 1, '9669.60657753', '0.01000000', 1525594956]]

I want to extract/print any sublist that has the first index 't'. So from the above it would return:

['t', '23068523', 0, '9660.00000000', '0.00191511', 1525594948]
['t', '23068524', 0, '9660.00000000', '0.00160000', 1525594948]
['t', '23068525', 0, '9658.52360670', '0.00020655', 1525594948]
['t', '23068526', 0, '9652.51635910', '0.00020668', 1525594948]
['t', '23068527', 0, '9652.50517986', '0.10115560', 1525594948]
['t', '23068528', 1, '9669.60657753', '0.01000000', 1525594956]
Ad

Answer

simple loop

for l in nested_list:
    if l[0] == 't':
        print (l)

if there is an outer list just add a loop. one liner with filter

filter(lambda x: x[0] == 't', nested_list) 
Ad
source: stackoverflow.com
Ad