我想检查例如int 2是否在另一个2之后或之前:
list = [2, 2, 3]
if 2 and 2 in list:
print "True"
如果列表是这样的:
list = [2, 3, 2]
print "False"
THX
答案 0 :(得分:1)
试试这个:
def check(list_):
last = None
for element in list_:
if element == last:
return True
else:
last = element
return False
答案 1 :(得分:0)
a = [0, 2, 15, 13, 13, 5, 12, 3, 1, 3, 14, 14, 17, 20, 0, 14, 2, 0,
1, 10, 5, 13, 15, 13, 19, 11, 20, 5, 4, 17, 20, 7, 4, 20, 20,
19, 3, 20, 20, 0, 14, 8, 18, 0, 18, 2, 5, 15, 12, 20, 5, 7, 12,
6, 17, 18, 15, 12, 2, 16, 6, 11, 14, 20, 8, 4, 11, 10, 15, 6,
10, 19, 1, 20, 6, 19, 2, 5, 13, 7, 5, 18, 11, 11, 3, 0, 11, 3,
14, 18, 15, 11, 2, 9, 12, 0, 18, 1, 4, 2]
在列表中运行一次,找到所有对并将它们放入一组
z = {x for x, y in zip(a, a[1:]) if x == y}
>>> z
{11, 20, 13, 14}
然后像这样使用它:
>>> n = 2
>>> n in z
False
>>> n = 13
>>> n in z
True
>>>
zip(a, a[1:])
将生成(a[0], a[1]), (a[1], a[2]), (a[2], a[3]), ...
pairwise
Itertools Recipe会做同样的事情。