Haikal Yeo
Haikal Yeo

Reputation: 247

Searching for an element within lists of lists

I have a list with elements of the following form:

[['37a1', 1], 153, 160, [[13, 2], [53, -1], [67, 2], [127, -1], [443, -1], [547, 2], [599, -1]]]
[['57a1', 1], 155, 157, [[5, 2], [11, -1]]]
[['198a1', 1], 156, 156, []]
[['551c1', 1], 155, 158, [[5, 5], [43, -1], [149, -1]]]

How may I search for elements in the list such that [anything,-1] is part of my element? In this case, the first two and last elements should return as my answer.

I know how to pull out just one element in the list that matches ['37a1',1] for instance:

matches = [x for x in regs if ['37a1', 1] in x]; matches

I'm guessing based on this that I should be doing something very similar to the above, but replacing ['37a1', 1] with someway of indicating 'anything'. As another example, I want to be able to search [anything,5] within my element and return the last element in this list as my output.

Upvotes: 0

Views: 59

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

I'm assuming you wanted to test for sublists in the last element of each list, not the first 3 elements.

You'll need to test against each element in each nested list; using any() would make that a little more efficient:

[x for x in regs if any(sub[1] == -1 for sub in x[-1])]

The any() test loops over the generator expression until a True value is found, at which point it stops iterating and returns True. This means that x is only included if there is a sublist in x[-1] whose second element is equal to -1.

Upvotes: 2

perreal
perreal

Reputation: 97918

This should work with arbitrary nested lists:

def has_items(m):
    for x in m:
        if isinstance(x, list):
            if not isinstance(x[0], list):
                if len(x) == 2 and x[1] == -1: return x
            elif has_items(x): return x
    return False


print has_items(reversed(m))

Upvotes: 2

Related Questions