Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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
Python 在遍历列表时跳过某些值_Python_Python 2.7_Image Processing_Iterator_Python Imaging Library - Fatal编程技术网

Python 在遍历列表时跳过某些值

Python 在遍历列表时跳过某些值,python,python-2.7,image-processing,iterator,python-imaging-library,Python,Python 2.7,Image Processing,Iterator,Python Imaging Library,我正在使用PIL编写一个Python程序,它需要为每个像素找到该像素5个像素范围内所有像素的值。为了找到所有这些像素的位置,我编写了以下代码: #w and h are dimensions of the image for y in range(h): for x in range(w): #find neighboring pixels neighbors = [(x+x2,x+y2) for x2 in range(-5,5) for y2 in r

我正在使用PIL编写一个Python程序,它需要为每个像素找到该像素5个像素范围内所有像素的值。为了找到所有这些像素的位置,我编写了以下代码:

#w and h are dimensions of the image
for y in range(h):
    for x in range(w):
        #find neighboring pixels
        neighbors = [(x+x2,x+y2) for x2 in range(-5,5) for y2 in range(-5, 5)]
        for i, (x2, y2) in enumerate(neighbors):
            if x2 < 0 or y2 < 0:
                neighbors.pop(i)
            if x2 > w or y2 > h:
                neighbors.pop(i)
#w和h是图像的尺寸
对于范围(h)内的y:
对于范围(w)内的x:
#查找相邻像素
邻域=[(x+x2,x+y2)对于范围内的x2(-5,5)对于范围内的y2(-5,5)]
对于枚举(邻域)中的i(x2,y2):
如果x2<0或y2<0:
邻居。流行音乐(一)
如果x2>w或y2>h:
邻居。流行音乐(一)

理论上,它会找到5个像素内的所有值,然后消除无效值。然而,即使在第一个像素上,
(0,0)
,也不是所有的负片都被消除,我稍后会得到一个
索引器。似乎当我遍历
邻居
时,它并没有传递
邻居
中的每一项。这是为什么?我如何更正它?

问题可能是,您在迭代列表时更改了列表。因此,我不会创建此列表并在之后删除非法条目,而是直接创建一个仅包含允许条目的列表。
为此,您可以在列表中使用
if
语句:

[(x+x2,y+y2) for x2 in range(-5,5) for y2 in range(-5, 5) if x+x2>0 and x+x2<w and y+y2>0 and y+y2<h]

[(x+x2,y+y2)范围内的x2(-5,5)范围内的y2(-5,5)如果x+x2>0和x+x20和y+y20以及y>0和xIf试图回答您下面的问题,但现在我发现您的代码中有一个打字错误,这可能是另一个错误原因。在您的列表理解中,您使用了两次
x+…
,而它可能是
(x+x2,y+y2)
。非常感谢。当你第一次回答时,它不起作用,但你的解决方案与我错过的那个打字错误结合在一起,效果非常好。谢谢:)起初我复制了这个打字错误,然后我用其他值尝试了一下,发现了错误。:)我很高兴能帮上忙。是的,我就是这么想的。
[(x,y) for (x,y) in neighbors if x>0 and y>0 and x<w and y<h]