Home > front end >  checking elements at list of listes by python cod
checking elements at list of listes by python cod

Time:12-04

I need to check if list contain any item in another list, i have the following lists:

A = [[1,2,3] , [5,6,7], ...]

B = [ 1 , 8, 9]

I mean if 1 or 2 or at the first list at A list appear at B so append 'NF' at pred list and so on , as I write the following code:

if any(item in list for list in A for item in B):
  pred.append('NF')
else: 
  pred.append('F')

The problem is the result is always NF if the element is on the list or not.

The output:

['NF', 'F']

CodePudding user response:

Maybe you need to get the outer loop outside of the any function?

A = [[1,2,3] , [5,6,7]]
B = [ 1 , 8, 9]

pred = []
for lst in A:
    if any(item in lst for item in B):
        pred.append('NF')
    else: 
        pred.append('F')

Output:

['NF', 'F']

As a one-liner:

pred = ['NF' if any(item in lst for item in B) else 'F' for lst in A]
  • Related