如何在嵌套列表Python中定位索引

2024-04-27 19:49:03 发布

您现在位置:Python中文网/ 问答频道 /正文

从输入导入列表

def find_peak(m: List[List[int]]) -> List[int]:
    """
    Given an non-empty elevation map m, returns the cell of the
    highest point in m.

Examples (note some spacing has been added for human readablity)
>>> m = [[1,2,3],
         [9,8,7],
         [5,4,6]]
>>> find_peak(m)
[1,0]
>>> m = [[6,2,3],
         [1,8,7],
         [5,4,9]]
>>> find_peak(m)
[2,2]
"""
max_location = []
for sublist in m:
    max_location.append(max(sublist))
max_location = max(max_location)
for sublist in m:
    if max_location in sublist:
        return (m.index(max_location),sublist.index(max_location))

这实际上不起作用,因为它只返回不在列表中的数字


Tags: theinan列表forindexdeflocation
3条回答

可以在展开的输入结构中找到最大值,然后返回指定先前找到的最大值位置的坐标:

from typing import List
def find_peak(m: List[List[int]]) -> List[int]:
  _max = max([i for b in m for i in b])
  return [[i, a] for i in range(len(m)) for a in range(len(m[0])) if m[i][a] == _max][0]

print(list(map(find_peak, [[[1, 2, 3], [9, 8, 7], [5, 4, 6]], [[6, 2, 3], [1, 8, 7], [5, 4, 9]]])))

输出:

^{pr2}$

您还可以充分利用enumerate。首先查找具有最大数目的行(及其索引)。然后在第二行找到那个数。在

在这两种情况下,您都需要为max函数提供一个键,以便它考虑值(而不是索引):

def find_peak(m):
    i, max_row = max(enumerate(m), key=lambda x: max(x[1]))
    j, max_val = max(enumerate(max_row), key=lambda x: x[1])
    return [i, j]

输出

^{pr2}$

我认为当你考虑迭代索引而不是列表上的项目时,它更容易:

from itertools import product

d = [[1, 2, 3], [7, 9, 8], [4, 5, 6]]

# generate all indices
x_len = range(len(d))
y_len = range(len(d[0]))
indices = product(x_len, y_len)

# select maximal item by index
key = lambda x: d[x[0]][x[1]]
max_index = max(indices, key=key)

print(max_index)

相关问题 更多 >