我正在编写一个脚本,如果数组的元素是主数组的子集,那么它会打印PASS,否则会打印FAIL。
我应该在下面的if-else语句中添加什么才能使其有效?
a = [1,2,3,4,5]
b = [1,2]
c = [1,9]
# The Passing Scenario
if (i in a for i in b):
print "PASS"
else:
print "FAIL"
# The Failing Scenario
if (i in a for i in c):
print "PASS"
else:
print "FAIL"
答案 0 :(得分:3)
使用all
。
# the passing scenario
if all(i in a for i in b):
print 'PASS'
else:
print 'FAIL'
# the failing scenario
if all(i in a for i in c):
print 'PASS'
else:
print 'FAIL'
答案 1 :(得分:2)
使用set
s,很简单:
>>> a = [1,2,3,4,5]
>>> b = [1,2]
>>> c = [1,9]
>>> set(b).issubset(set(a))
True
>>> set(c).issubset(set(a))
False
答案 2 :(得分:2)
这可以通过像
这样的设置操作来完成a = [1,2,3,4,5]
b, c = [1,2],[1,9]
print set(b) <= set(a)
# True
print set(c) <= set(a)
# False