简体   繁体   English

检查列表中是否有相同数字附近的数字 - python

[英]Check if there is a number near the same number in a list - python

I want to check if for example the int 2 comes after or before another 2:我想检查例如 int 2 是在另一个 2 之后还是之前:

list = [2, 2, 3]
if 2 and 2 in list:
    print "True"

And if the list is this:如果列表是这样的:

list = [2, 3, 2]
print "False"

thx谢谢

Try this:尝试这个:

def check(list_):
    last = None
        for element in list_:
            if element == last:
                return True
            else:
                last = element
    return False
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]

Run through the list once to find all the pairs and put them in a set遍历列表一次以找到所有并将它们放入一个集合中

z = {x for x, y in zip(a, a[1:]) if x == y}

>>> z
{11, 20, 13, 14}

Then use it like this:然后像这样使用它:

>>> n = 2
>>> n in z
False
>>> n = 13
>>> n in z
True
>>> 

zip(a, a[1:])

will produce tuples of (a[0], a[1]), (a[1], a[2]), (a[2], a[3]), ...将产生(a[0], a[1]), (a[1], a[2]), (a[2], a[3]), ...

The pairwise Itertools Recipe will do the same thing. pairwise Itertools Recipe会做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM