Sé que ya está satisfecho con uno de la respuesta de en este post pero, puede intentar con los siguientes
>>> v = [1,2,3,4,3,1,2]
def InList(v,(i,j)):
start=1
try:
while True:
if v[v.index(i,start)+1]==j and v[v.index(j,start)-1]==i:
return True
start=v.index(i)+1
except IndexError:
return False
except ValueError:
return False
>>> InList(v,(2,3))
True
>>> InList(v,(4,5))
False
>>> InList(v,(1,2))
True
>>> InList(v,(12,2))
False
>>> InList(v,(3,1))
True
Ok curiosidad lo mejor de mí y así que quería probar cómo lo hace aplicación realiza con la aplicación más rápida publicado
>>> stmt1="""
v = [1,2,3,4,3,1,2]
def InList(v,(i,j)):
start=1
try:
while True:
if v[v.index(i,start)+1]==j and v[v.index(j,start)-1]==i:
return True
start=v.index(i)+1
except IndexError:
return False
except ValueError:
return False
InList(v,(2,3))
InList(v,(4,5))
InList(v,(1,2))
InList(v,(12,2))
"""
>>> stmt2="""
v = [1,2,3,4,3,1,2]
def InList(v,(x,y)):
any([x,y] == v[i:i+2] for i in xrange(len(v) - 1))
InList(v,(2,3))
InList(v,(4,5))
InList(v,(1,2))
InList(v,(12,2))
"""
>>> t1=timeit.Timer(stmt=stmt1)
>>> t2=timeit.Timer(stmt=stmt2)
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
13.67 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
20.67 usec/pass
>>>
Gosh esta es una forma rápida
Nota ** Gracias Michael por señalarlo. Lo he corregido y aquí está mi solución actualizada.
¿No será el empalme de crear una nueva lista secundaria cada vez? ¿No será 2 si es mejor? corrígeme si estoy equivocado. – st0le
Creo que 'v [i: i + 2]' solo ve los elementos de la lista. – eumiro
@eumiro Tu creencia es incorrecta :-) List slices create new lists. Por ejemplo, ese es el mecanismo detrás del modismo para crear una copia de lista: '' c = s [:] ''. –