gpt4 book ai didi

python - 如何在 python 中查找二维列表的邻居?

转载 作者:太空狗 更新时间:2023-10-30 01:42:47 24 4
gpt4 key购买 nike

我有一个只有 1 和 0 的二维列表:

Boundaries = [
[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,1,1],
[0,1,1,1,0],
[0,0,1,0,0]]

我需要测试这个列表来检查是否有任何 1 被其他 8 个 1 包围(比如这个列表中的中间 1)。如果有一个 1 被 1 作为邻居包围,那么它应该被更改为 0,这样在运行程序后上面的列表将返回如下所示:

[
[0,0,0,0,0],
[0,1,1,1,0],
[0,1,0,1,1],
[0,1,1,1,0],
[0,0,1,0,0]]

我试图只使用一个参数(1 和 0 的矩阵)。出于某种原因,这是一件非常困难的事情。到目前为止,我的代码看起来像这样:

def tempBoundaries(matrixC):
for i in matrixC:
for j in i:
if j == 1:
try:
if matrixC[i-1]==1 or matrixC[i+1]==1:
.......

无论出于何种原因,这都是一场真正的斗争,我似乎无法弄清楚该怎么做,任何提示或帮助将不胜感激!谢谢。

最佳答案

使用 scipy 你会做类似下面的事情

import numpy

boundaries = numpy.array([
[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,1,1],
[0,1,1,1,0],
[0,0,1,0,0]])

counts = scipy.signal.convolve2d(boundaries, numpy.ones((3,3)), mode='same')

# which gives you a matrix with counts of the number of 1s around each point
array([[ 1., 2., 3., 2., 1.],
[ 2., 4., 6., 5., 3.],
[ 3., 6., 9., 7., 4.],
[ 2., 5., 7., 6., 3.],
[ 1., 3., 4., 3., 1.]])

# so then you just find the points where it's == 9
counts == 9
array([[False, False, False, False, False],
[False, False, False, False, False],
[False, False, True, False, False],
[False, False, False, False, False],
[False, False, False, False, False]], dtype=bool)

# so you can update those positions
boundaries[counts == 9] = 0

所以整个操作很简单:

boundaries = numpy.array(Boundaries)
counts = scipy.signal.convolve2d(boundaries, numpy.ones((3,3)), mode='same')
boundaries[counts == 9] = 0

关于python - 如何在 python 中查找二维列表的邻居?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com