鉴于您的示例列表:
list_1 = [[1, 2, 9], [4, 5, 8]]
list_2 = [[1, 2, 3], [4, 5, 6], [1, 2, 5]]
这有效:
print [this[0:2]==that[0:2] for this in list_1 for that in list_2]
[True, False, True, False, True, False]
或者,使用一组:
print [this for this in list_1 for that in list_2 if set(this[0:2])<set(that)]
[[1, 2, 9], [1, 2, 9], [4, 5, 8]]
请注意,集合是无序的,因此:
>>> set([1,2])==set([2,1])
True
的典型用法in
是字符串:
>>> 'ab' in 'cbcbab'
True
或序列中的单个元素:
>>> 100 in range(1000)
True
或序列中的一个原子元素:
>>> (3,3,3) in zip(*[range(10)]*3)
True
但是重叠列表元素不起作用:
>>> [1,2] in [0,1,2,3]
False
除非元素的原子大小相同:
>>> [1,2] in [0,[1,2],3]
True
但是您可以使用字符串来比较列表 a 是否在列表 b 中,如下所示:
>>> def stringy(li): return ''.join(map(str,li))
...
>>> stringy([1,2,9][0:2])
'12'
>>> stringy([1,2,9][0:2]) in stringy([1,2,5])
True
因此,您的初衷可能是检查是否item[0:2]
出现在otherItem
循环中的任何地方,但按“项目”的顺序。您可以使用这样的字符串:
>>> print [this for this in list_1 for that in list_2 if stringy(this[0:2]) in stringy(that)]
[[1, 2, 9], [1, 2, 9], [4, 5, 8]]
这与 set 版本不同'12'!='21'
,'12' not in '21'
因此如果您更改了 list_2 的元素顺序:
list_1 = [[1, 2, 9], [4, 5, 8]]
list_2 = [[1, 2, 3], [4, 5, 6], [1, 5, 2]]
print [this for this in list_1 for that in list_2 if set(this[0:2])<set(that)]
[[1, 2, 9], [1, 2, 9], [4, 5, 8]] # same answer since sets are unordered
print [this for this in list_1 for that in list_2 if stringy(this[0:2]) in stringy(that)]
[[1, 2, 9], [4, 5, 8]] # different answer...