gpt4 book ai didi

python - 在Python中识别列表列表中的峰值海拔

转载 作者:行者123 更新时间:2023-11-30 23:27:19 24 4
gpt4 key购买 nike

我需要定义一个函数来识别海拔数据中的峰值。峰值定义为高于 8 个相邻值的值(上方 3 个,两侧各 1 个,下方 3 个)。

不允许导入

在以下数据中:87是一个峰值,因为它高于54,82,72,49,69,62,71,61

data = [ [20, 54, 50, 64, 60, 63, 60, 48, 20, 20],
[20, 56, 72, 76, 72, 52, 62, 53, 20, 20],
[20, 52, 62, 81, 67, 48, 67, 52, 23, 20],
[20, 54, 54, 82, 72, 42, 64, 50, 22, 20],
[20, 53, 49, 87, 69, 47, 48, 49, 21, 20],
[20, 20, 62, 71, 61, 36, 28, 31, 22, 20],
[20, 20, 20, 20, 20, 22, 21, 28, 24, 20],
[20, 20, 20, 20, 20, 20, 20, 20, 20, 20],
[20, 20, 20, 20, 20, 20, 20, 20, 20, 20],
[20, 20, 20, 20, 20, 20, 20, 20, 20, 20]
]

我知道如何做到这一点,但不太确定如何编写代码。

def peaks(list1):
for item in list1:
# if item > (item[row][column-1] and item[row][column+1] and item[row-1][column-1] and \
# item[row-1][column] and item[row-1][column+1] and item[row+1][column-1] and item[row+1][column] and item[row+1][column+1]):

如何将注释部分翻译成正确的 python 代码?

编辑:好吧,为什么这不起作用?列表坐标似乎被覆盖,我不明白为什么。

返回应该是:[(2, 6), (4, 3)]

def peaks(list1):
for row in range(len(list1)):
for column in range (len(list1[row])):
if row != 0 and row != len(list1)-1 \
and column != 0 and column != len(list1[row])-1:
coords = []
if max(list1[row-1][column-1:column+2] + \
[list1[row][column-1]] + [list1[row][column+1]] + \
list1[row+1][column-1:column+2]) < list1[row][column]:
coords.append((row, column))
return coords

最佳答案

您可以使用一些 Python 特定的习惯用法,并尝试使此代码更具可读性。我们将问题划分如下:

  1. 给定一个矩阵,返回所有核心(非边界)索引;
  2. 给定矩阵核心内的坐标,返回包含其邻居坐标的列表;
  3. 给定一对或坐标和一个矩阵,检查它是否是一个峰值。

第一步可以按如下方式实现:

def core_indexes(matrix):
row = matrix[0]

lines = len(matrix)
columns = len(row)

for i in range(1, lines - 1):
for j in range(1, columns - 1):
yield i, j

请注意,此方法没有返回值,而是产生。产生的函数或方法是编写生成器的 Python 形式,即每次调用时都会返回一系列下一项的特殊函数。

第二步就更简单了,我们用同样的技巧吧。

def neighbor_indexes(i, j):
for r in range(i - 1, i + 2):
for c in range(j - 1, j + 2):
if (i, j) != (r, c):
yield r, c

我们应该做的下一件事(第三步)是检查给定位置是否代表峰值。当且仅当给定值大于其最大邻居时,该值才是峰值。让我们这样写:

def is_peak(i, j, matrix):
max_neighbor = max([matrix[i][j] for i, j in neighbor_indexes(i, j)])
return matrix[i][j] > max_neighbor

请注意以下声明:

[matrix[i][j] for i, j in neighbor_indexes(i, j)]

这称为列表理解。它被翻译为“为 neighbour_indexes 函数返回的每个 i, j 对构建一个矩阵 [i,j] 列表”。相当Pythonic。

现在,是时候使用这些函数来扫描矩阵了。人们可以执行以下操作:

for i, j in core_indexes(data):
if is_peak(i, j, data):
print("%d at [%d, %d] is a peak" % (data[i][j], i, j))

它将打印:

67 at [2, 6] is a peak
87 at [4, 3] is a peak

请注意,我们的索引是从零开始的。

关于python - 在Python中识别列表列表中的峰值海拔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133392/

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