Ask Your Question
1

check condition for a list of lists

asked 2 years ago

rizwan gravatar image

updated 2 years ago

slelievre gravatar image

I have a list of lists L = [L1, L2, L3,... Lm] where each Li is a list again. I want to check each Li for a condition.

I need only those Li where all elements of Li satisfy a certain property.

I am trying the following but it's not working the way I want.

for i in range(0, len(L)):
    U = L[i]
    for s in U:
          check(s)

But this does not distinguish between the elements of Li.

A little help is needed.

Thanks

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 2 years ago

achrzesz gravatar image

updated 2 years ago

slelievre gravatar image

Learn about the Python command all using help(all).

Below are a couple of examples.

First define a list of lists (of integers):

L1 = [1, 2]
L2 = [-1, 1]
L3 = [3, 1]
L = [L1, L2, L3]

Then keep only those consisting only of positive integers:

  • using map:

    [Li for Li in L if all(map(lambda v: v > 0, Li))]
  • using list comprehension:

    [Li for Li in L if all(v > 0 for v in Li)]

For your use case, this might become

LL = [Li for Li in L if  all(check(s) for s in Li)]
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2 years ago

Seen: 369 times

Last updated: Nov 26 '22