在Python中使用'in'测试一个子列表中的另一个子列表的一部分 [英] Using 'in' to test for part of one sublist in another in Python
本文介绍了在Python中使用'in'测试一个子列表中的另一个子列表的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此处的新手尝试在另一个子列表中搜索一个子列表的一部分.
Newbie here trying to search for part of one sublist within another sublist.
list_1 = [[1, 2, 9], [4, 5, 8]]
list_2 = [[1, 2, 3], [4, 5, 6], [1, 2, 5]]
for item in list_1:
for otherItem in list_2:
item[0:2] in otherItem[0:2]
我希望这会回来
True
False
True
False
True
False
但是,每次迭代我都会得到错误的结果. 简而言之:
But instead I get false for every iteration. In a nutshell:
list_1[0][0:2] == list_2[0][0:2] #this returns true
list_1[0][0:2] in list_2[0][0:2] #this returns false
我想我不明白in
的工作原理.有人可以在这里教我吗?
I guess I don't understand how in
works. Can anyone school me here?
推荐答案
in
查看一个子列表是否是另一列表的 (不是子列表):
in
looks to see if one sublist is an element (not sublist) of another list:
[1,2] in [[1,2],[3,4]]
将是True
.
[1,2] in [1,2,3]
将是False
,
[1,2] in [1,2]
但是:
[1,2] == [1,2]
将是True
.根据您实际尝试执行的操作,set
对象可能会有用.
would be True
. Depending on what you're actually trying to do, set
objects might be useful.
a = [1,2]
b = [1,2,3]
c = [3,2,1]
d = [1,1,1]
e = set(a)
len(e.intersection(b)) == len(a) #True
len(e.intersection(c)) == len(a) #True -- Order of elements does not matter
len(e.intersection(d)) == len(a) #False
这篇关于在Python中使用'in'测试一个子列表中的另一个子列表的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文