您可以尝试以下内容
>>> 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
好吧,我的好奇心驱使我想测试一下这个实现与最快发布的实现相比表现如何
>>> 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
>>>
哇,这速度真快。
v[i:i+2]
只是查看列表元素。 - eumiroc = s[:]
。 - Raymond Hettinger