Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3-列表上的特定操作_Python_Python 3.x - Fatal编程技术网

Python3-列表上的特定操作

Python3-列表上的特定操作,python,python-3.x,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

我有一个长度为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.

任何提示都很有用。

您可以使用
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])]

你不需要提示,你需要一个算法你能告诉我们到目前为止你尝试了什么吗?我认为你在问题陈述或示例中有错误,因为
2-5!=4-1
@user2357112感谢您指出这一点!我已编辑我的条件。如果其中一对变为奇数索引、偶数索引而不是偶数索引,则此操作无效,这给了我一个错误:TypeError:'zip'对象不是subscriptable@FallenAngel我没有注意到你在python 3中,你需要将z转换为列表。@user2357112是的,它可以有任何形状,也可以用
izip
完成。但我只是为此编写的case@Kasra,我不确定你是否明白user2357112的意思。如果您使用
l[1://code>而不是
l
,您的算法将无法再找到解决方案!