Ask Your Question
1

check condition for a list of lists

asked 2022-11-19 23:21:08 +0200

rizwan gravatar image

updated 2022-11-26 13:01:22 +0200

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

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-26 11:22:22 +0200

achrzesz gravatar image

updated 2022-11-26 13:07:46 +0200

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)]
edit flag offensive delete link more

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: 2022-11-19 23:21:08 +0200

Seen: 153 times

Last updated: Nov 26 '22