admin管理员组文章数量:1312674
Why does this always print false?
I expected a different outcome because the first two items in the 4th element in List1
are 61, 64
and those match 2 items in the 1st element of List2
which has 61, 62, 64, 70
List1 = [
[60, 64, 67],
[62, 67, 72],
[62, 66, 69],
[61, 64, 69],
[64, 66, 71],
[63, 66, 71],
]
List2 = [
[61, 62, 64, 70],
[60, 61, 62, 63],
[64, 65, 67, 69],
[65, 70, 66, 61],
]
for x in List1:
is_subset = all([(y in List2) for y in x[0:2]])
print(is_subset)
Why does this always print false?
I expected a different outcome because the first two items in the 4th element in List1
are 61, 64
and those match 2 items in the 1st element of List2
which has 61, 62, 64, 70
List1 = [
[60, 64, 67],
[62, 67, 72],
[62, 66, 69],
[61, 64, 69],
[64, 66, 71],
[63, 66, 71],
]
List2 = [
[61, 62, 64, 70],
[60, 61, 62, 63],
[64, 65, 67, 69],
[65, 70, 66, 61],
]
for x in List1:
is_subset = all([(y in List2) for y in x[0:2]])
print(is_subset)
Share
Improve this question
edited Jan 31 at 16:07
Barmar
783k56 gold badges547 silver badges660 bronze badges
asked Jan 31 at 15:02
TimTim
11 silver badge6 bronze badges
4
|
2 Answers
Reset to default 1You were comparing numbers with list items that are lists as well. This alternative code might satisfy your purpose.
List1 = [
[60, 64, 67],
[62, 67, 72],
[62, 66, 69],
[61, 64, 69],
[64, 66, 71],
[63, 66, 71],
]
List2 = [
[61, 62, 64, 70],
[60, 61, 62, 63],
[64, 65, 67, 69],
[65, 70, 66, 61],
]
for x in List1:
for z in List2:
is_subset =all([(y in z) for y in x[0:2]])
if is_subset == True:
break
print(is_subset)
Result:
False
False
False
True
False
False
Use sets and the issubset()
method.
You should use any()
to test if x[0:2]
is a subset of any of the lists in List2
, not all()
.
List1 = [
[60, 64, 67],
[62, 67, 72],
[62, 66, 69],
[61, 64, 69],
[64, 66, 71],
[63, 66, 71],
]
List2 = [
[61, 62, 64, 70],
[60, 61, 62, 63],
[64, 65, 67, 69],
[65, 70, 66, 61],
]
Sets2 = list(map(set, List2))
for x in List1:
xset = set(x[0:2])
is_subset = any(xset.issubset(y) for y in Sets2)
print(is_subset)
Result:
False
False
False
True
False
False
本文标签: pythonFinding a subset of values in another listStack Overflow
版权声明:本文标题:python - Finding a subset of values in another list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741911827a2404488.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.issubset()
to tell if one set is a subset of another. – Barmar Commented Jan 31 at 16:10any()
andall()
can be a generator, you don't need to construct a list. This allows them to stop generating as soon as the answer is determined. – Barmar Commented Jan 31 at 16:12