0

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?

BillyJo_rambler
  • 563
  • 6
  • 23
  • What do you think `all(['A', 'C', 'D'])` is? – Julien Jan 15 '19 at 06:17
  • I suspect this [answer](https://stackoverflow.com/a/22673813/7644596) is where you got your idea from. If you didn't, it is a good example anyway, and easy to find in stackoverflow. Just make sure you implement it well. – jberrio Jan 15 '19 at 06:28
  • Possible duplicate of [Simplest way to check if multiple items are (or are not) in a list?](https://stackoverflow.com/questions/22673770/simplest-way-to-check-if-multiple-items-are-or-are-not-in-a-list) – jberrio Jan 15 '19 at 06:28

3 Answers3

2

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')
cs95
  • 379,657
  • 97
  • 704
  • 746
2

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')
Yuda
  • 343
  • 4
  • 15
2

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
Roger Wang
  • 565
  • 2
  • 12
  • 30