python 列表中的冲突案例
conflicting cases in python lists
我有两个集合列表 -
attribute = [{0, 1, 2, 3, 6, 7}, {4, 5}]
和
decision = [{0, 1, 2}, {3, 4}, {5}, {6, 7}]
我要-
{3, 4}
在这里,{3, 4}
是冲突的,因为它既不是 {0, 1, 2, 3, 6, 7}
的子集,也不是 {4, 5}
.
的子集
我的代码-
check = []
for i in attribute:
for j in decision:
if j.issubset(i):
check.append(j)
print(check)
for x in decision:
if not x in check:
temp = x
print(temp)
这给了我 {3, 4}
,但是有没有更简单(和/或)更快的方法来做到这一点?
result = [i for i in decision if not [j for j in attribute if i.issubset(j)]]
result 是所有集合的列表,它们不是属性的子集。 :)
这是 :
的精简版
result = []
for i in decision:
tmp_list = []
for j in attribute:
if i.issubset(j):
tmp_list.append(j)
if not tmp_list:
result.append(i)
您可以使用以下列表理解:
[d for d in decision if not any(d <= a for a in attribute)]
这个returns:
[{3, 4}]
如果您只想要第一个满足条件的集合,您可以使用 next
和生成器表达式来代替:
next(d for d in decision if not any(d <= a for a in attribute))
这个returns:
{3, 4}
我有两个集合列表 -
attribute = [{0, 1, 2, 3, 6, 7}, {4, 5}]
和
decision = [{0, 1, 2}, {3, 4}, {5}, {6, 7}]
我要-
{3, 4}
在这里,{3, 4}
是冲突的,因为它既不是 {0, 1, 2, 3, 6, 7}
的子集,也不是 {4, 5}
.
我的代码-
check = []
for i in attribute:
for j in decision:
if j.issubset(i):
check.append(j)
print(check)
for x in decision:
if not x in check:
temp = x
print(temp)
这给了我 {3, 4}
,但是有没有更简单(和/或)更快的方法来做到这一点?
result = [i for i in decision if not [j for j in attribute if i.issubset(j)]]
result 是所有集合的列表,它们不是属性的子集。 :)
这是 :
的精简版result = []
for i in decision:
tmp_list = []
for j in attribute:
if i.issubset(j):
tmp_list.append(j)
if not tmp_list:
result.append(i)
您可以使用以下列表理解:
[d for d in decision if not any(d <= a for a in attribute)]
这个returns:
[{3, 4}]
如果您只想要第一个满足条件的集合,您可以使用 next
和生成器表达式来代替:
next(d for d in decision if not any(d <= a for a in attribute))
这个returns:
{3, 4}