Python 3 - 列表上的特定操作

时间:2015-06-03 06:05:09

标签: python python-3.x

我有一个长度为n的列表,其中包含正数:

list = [a,b,c,d,g,h,w,x,y,z]

其中a,b,c ......都是数字。我想检查列表是否有任何两个连续的数字对满足以下标准:

[w,x] and [y,z] such that w = z +/- 1 and x = y +/- 1 and abs(w-x) == abs(y-z)

例如 -

>>> l
[0, 3, 2, 5, 4, 1, 6]
(2,5) and (4,1) are such consecutive pairs of list elements.

任何提示都会有用。

1 个答案:

答案 0 :(得分:1)

您可以使用zip功能:

>>> z=list(zip(l[0::2],l[1::2]))
>>> new=zip(z,z[1:])
>>> [([w,x],[y,z]) for [w,x],[y,z] in new if abs(w-z)==1 and abs(x-y)== 1 and abs(w-x) == abs(y-z)]
[([2, 5], [4, 1])]

注意对于长列表,您可以使用itertools.izip代替zip

另一个例子:

>>> l=[0, 3, 2, 5, 4, 1]
>>> z=zip(l[0::2],l[1::2])
>>> new=zip(z,z[1:])
>>> [([w,x],[y,z]) for [w,x],[y,z] in new if abs(w-z)==1 and abs(x-y)== 1 and abs(w-x) == abs(y-z)]
[([2, 5], [4, 1])]

根据其他案例的评论说明,您可以采取更完整的方式:

>>> l=[8, 0, 3, 2, 5, 4, 1, 6]
>>> z1=zip(l[0::2],l[1::2])
>>> new1=zip(z1,z1[1:])

>>> z2=zip(l[1::2],l[2::2])
>>> new2=zip(z2,z2[1:])

>>> total=new1+new2
>>> [([w,x],[y,z]) for [w,x],[y,z] in total if abs(w-z)==1 and abs(x-y)== 1 and abs(w-x) == abs(y-z)]
[([2, 5], [4, 1])]