[英]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 C
exist together with D
. 这个想法是要确定
A
和C
与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
? 我已经尝试了上面的代码,但由于总是假设它仅测试是否有任何检查清单的单个项目在
L1
范围内,所以我总是遇到违规情况。
If you want to check for these subsets, you will have to check each one separately. 如果要检查这些子集,则必须分别检查每个子集。 Your use of
all
is also improper. 您对
all
内容的使用也不正确。 all
checks whether all elements of the sequence passed to it are "Truthy" . all
检查传递给它的序列中的所有元素是否都是“ Truthy” 。
all(['A', 'B', 'C'])
# True
So your if
actually reduces to: 因此,您的
if
实际上减少到:
if True or True or True in l1:
The expression short circuits to if True
, so this is always executed. 该表达式会短路到
if True
,因此始终会执行。
I would to this by performing a set.issuperset()
check for every subset on df
's columns. 为此,我将对
df
列上的每个子集执行set.issuperset()
检查。
subsets = [{'A', 'C', 'D'}, {'A', 'D'}, {'C', 'D'}]
columns = set(df)
if any(columns.issuperset(s) for s in subsets):
print('Violation')
I'm not sure that I understand your question exactly... 我不确定我是否完全理解您的问题...
This code checks if ['A', 'D'] and
['C', 'D'] exist in l1. 该代码检查l1中是否存在['A','D']
and
['C','D']。
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, 如果您想要
or
条件,
if all(i in l1 for i in ['A', 'D']) or all(i in l1 for i in ['C', 'D']):
print('Violation')
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. 当您说全部(['A','C','D'])时,每个字母都会转换为True布尔值,从而使all()语句为true,并且始终会打印“ Violation” 。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.