比较两个集合列表

时间:2018-10-21 16:10:06

标签: python python-3.x set

我的第一组清单:

set1 = [
    {'read', 'execute', 'helloworld.exe'}, 
     {'read', 'pinglog', 'write'}, 
     {'read', 'nya'}, 
     {'read', 'execute', 'write', 'goodluck'}
]

现在我正在查看下面的这些不同集合是否在集合的第一列表中。

final = [
    {'read', 'nya'}, 
    {'helloworld.exe', 'write'},
    {'execute', 'nya'}, 
    {'read', 'pinglog'}, 
    {'write', 'pinglog'}
]

预期结果是

OK
Access denied
Access denied
OK
OK
OK

这是我的代码,我所知不多,但是我已经两天想这样做了,我的头已经很痛了:

for j in range(len(final)):
    for i in range(len(set1)):
        if final[j] == set1[i]:
            print("OK")

    print("Access denied")

2 个答案:

答案 0 :(得分:0)

您似乎正在测试您的集合是否为子集;您可以使用<= operator on the sets

>>> final[0], set1[2]  # same
({'nya', 'read'}, {'nya', 'read'})
>>> final[0] <= set1[2]
True
>>> final[3], set1[1]  # subset
({'pinglog', 'read'}, {'write', 'pinglog', 'read'})
>>> final[3] <= set1[1]
True
>>> final[4], set1[1]  # subset
({'write', 'pinglog'}, {'write', 'pinglog', 'read'})
>>> final[4] <= set1[1]
True

使用any() functiongenerator expressionset1中的所有集合测试给定集合:

for request in final:    
    if any(request <= s for s in set1):
        print("OK")
    else:
        print("Access denied")

演示:

>>> for request in final:
...     if any(request <= s for s in set1):
...         print("OK")
...     else:
...         print("Access denied")
...
OK
Access denied
Access denied
OK
OK

答案 1 :(得分:0)

我们可以使用生成器表达式来检查x是否是set1中任何集合的子集,如果是,则打印OK否则Access Denied

for i in ('OK' if any(x <= y for y in set1) else 'Access Denied' for x in final):
    print(i)
OK
Access Denied
Access Denied
OK
OK