Python如果有带或条件的语句
我正在使用Python 3.5,并尝试创建一个if语句,以对照两个不同的列表检查两个不同的变量,我尝试了以下方法: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): 但似乎没有一个有效,要么只有第一个语句完成,要么
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)
?