Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如果有带或条件的语句_Python - Fatal编程技术网

Python如果有带或条件的语句

Python如果有带或条件的语句,python,Python,我正在使用Python 3.5,并尝试创建一个if语句,以对照两个不同的列表检查两个不同的变量,我尝试了以下方法: if not any(x in colorsA for x in colorsB) or (y in colorsA for y in colorsC): 而且 if not any(x in colorsA for x in colorsB) or not any(y in colorsA for y in colorsC): 但似乎没有一个有效,要么只有第一个语句完成,要么

我正在使用Python 3.5,并尝试创建一个if语句,以对照两个不同的列表检查两个不同的变量,我尝试了以下方法:

if not any(x in colorsA for x in colorsB) or (y in colorsA for y in colorsC):
而且

if not any(x in colorsA for x in colorsB) or not any(y in colorsA for y in colorsC):
但似乎没有一个有效,要么只有第一个语句完成,要么根本没有,所有变量都是字符串。有没有一个简单的方法可以做到这一点

例如:

ColorsA = ['red', 'yellow', 'green']
ColorsB = ['red', 'white', 'blue']
ColorsC = ['white', 'blue', 'green']
如果colorsB或colorsC中没有来自colorsA的颜色

印刷品(彩色)


输出:黄色

您可以使用列表理解语法。 我展示了派生数组结果和最后一个if条件语句示例

ColorsA = ['red', 'yellow', 'green']
ColorsB = ['red', 'white', 'blue']
ColorsC = ['white', 'blue', 'green']

print
print [x for x in ColorsA if x not in ColorsB]
print [x for x in ColorsA if x not in ColorsC]
print [x for x in ColorsA if ((x not in ColorsC) and (x not in ColorsB))]

if (len([x for x in ColorsA if ((x not in ColorsC) and (x not in ColorsB))])==0):
    print "some elements in ColorsA are not found in ColorsB or ColorsC"
else:
    print "All elements in ColorsA are found in either ColorsB or ColorsC"
这将为您提供输出

['yellow', 'green']
['red', 'yellow']
['yellow']
some elements in ColorsA are not found in ColorsB or ColorsC

你要找的是一份工作。在Python中,使用
set
类与集合交互:

ColorsA = ['red', 'yellow', 'green']
ColorsB = ['red', 'white', 'blue']
ColorsC = ['white', 'blue', 'green']

result = set(ColorsA) - (set(ColorsB) + set(ColorsC))
if result:
    print('At least one element in ColorsA is not found in either ColorsB or ColorsC')
else:
    print('All elements in ColorsA are found in either ColorsB or ColorsC')

如果集合非常大,第一次构建这些
set
对象可能会非常昂贵。另一方面,一旦创建了
set
对象,它们的使用速度就非常快。在color\u set中检查类似于
'yellow'的内容将大大快于在color\u list
中检查
'yellow'的内容,尤其是当集合的大小增加时。

您能否举个例子说明
colorsX
并向我们确切说明您试图应用的逻辑?您能否向我们展示这些列表以及标准是什么?可能有一种更简单的方法…
如果没有(any(colorsA中的x表示colorsB中的x)或any(colorsC中的y表示colorsD中的y)):
-是的,可能有更简单的方法。将列表分成多个集合,看看集合中是否有公共元素。例如,
any()
之前结束,你只需要最少的
或任何(…)
,但帕特里克的评论才是真正的方法。你的意思是
打印(colorsA)