BillyJo_rambler
BillyJo_rambler

Reputation: 583

Check if any two items are present within another list

How to check if any two items of a list are within another list?

I am trying work out how to test if certain combinations of words appear within a list. For example:

l1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

if all(['A', 'C', 'D']) or all(['A', 'D']) or all(['C', 'D'])in l1:
    print('Violation') 

The idea is to determine if either (or both) A and Cexist together with D.

I have tried the code above, but I am always getting a violation as I assume it is only testing if a single item for any of the check lists are within L1?

Upvotes: 0

Views: 213

Answers (3)

Roger Wang
Roger Wang

Reputation: 595

When you say, if all(['A', 'C', 'D']), each of the letters is converted to a True boolean, thus making the all() statement true, and "Violation" will always be printed. Here's a way to fix that:

l1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
pattern1 = ['A', 'C', 'D']
pattern2 = ['A', 'D']
pattern3 = ['C', 'D']

for pat in [pattern1, pattern2, pattern3]:
    if all(letter in l1 for letter in pat):
        print("Violation")
        break

Upvotes: 2

Yuda
Yuda

Reputation: 343

I'm not sure that I understand your question exactly...

This code checks if ['A', 'D'] and ['C', 'D'] exist in l1.

if all(i in l1 for i in ['A', 'D']) and all(i in l1 for i in ['C', 'D']):
    print('Violation')

If you want or condition,

if all(i in l1 for i in ['A', 'D']) or all(i in l1 for i in ['C', 'D']):
    print('Violation')

Upvotes: 2

cs95
cs95

Reputation: 402363

If you want to check for these subsets, you will have to check each one separately. Your use of all is also improper. all checks whether all elements of the sequence passed to it are "Truthy".

all(['A', 'B', 'C'])
# True

So your if actually reduces to:

if True or True or True in l1:

The expression short circuits to if True, so this is always executed.


I would to this by performing a set.issuperset() check for every subset on df's columns.

subsets = [{'A', 'C', 'D'}, {'A', 'D'}, {'C', 'D'}]
columns = set(df)
if any(columns.issuperset(s) for s in subsets):
    print('Violation')

Upvotes: 2

Related Questions