spa*_*tin 0 python nested-lists
新手在这里试图搜索另一个子列表中的一个子列表的一部分.
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]
Run Code Online (Sandbox Code Playgroud)
我希望这会回来
True
False
True
False
True
False
Run Code Online (Sandbox Code Playgroud)
但相反,我每次迭代都会得到假.简而言之:
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
Run Code Online (Sandbox Code Playgroud)
我想我不明白是怎么in运作的.谁能在这里教我?
in查看一个子列表是否是另一个列表的元素(不是子列表):
[1,2] in [[1,2],[3,4]]
Run Code Online (Sandbox Code Playgroud)
会的True.
[1,2] in [1,2,3]
Run Code Online (Sandbox Code Playgroud)
会是False这样的:
[1,2] in [1,2]
Run Code Online (Sandbox Code Playgroud)
然而:
[1,2] == [1,2]
Run Code Online (Sandbox Code Playgroud)
会的True.根据您实际尝试的操作,set对象可能很有用.
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
Run Code Online (Sandbox Code Playgroud)