查找嵌套列表Python3.x的最大值的索引

查找嵌套列表Python3.x的最大值的索引,python,python-3.x,Python,Python 3.x,我试图找到嵌套列表的最大值的索引 我有三个列表[[1,2,3,4],[5,6,7,8],[9,10,11,12]] 我想让我的输出给我值12的索引 输出为: 最大元素的位置位于(2,3) 谢谢 使用numpy的argmax,然后分解索引: >>> L = [[1,2,3,4], [5,6,7,8], [9,10,11,12]] >>> a = np.array(L) >>> np.unravel_index(np.argmax(a), a.s

我试图找到嵌套列表的最大值的索引

我有三个列表[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

我想让我的输出给我值12的索引

输出为:

最大元素的位置位于(2,3)


谢谢

使用numpy的argmax,然后分解索引:

>>> L = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
>>> a = np.array(L)
>>> np.unravel_index(np.argmax(a), a.shape)
(2, 3)

如果您不想使用numpy,可以像下面这样手动执行搜索:

a = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

maxEntry = None
coords = (None, None)
for x, sublist in enumerate(a):
    for y, entry in enumerate(sublist):
        if maxEntry == None or entry > maxEntry:
            maxEntry = entry
            coords = (x,y)

print(coords)

没有numpy的解决方案是(假设列表及其第一个元素从不为空):

返回

(2, 3)
(0, 4)

如果您想要一个解决方案,它可以适用于任何深度的嵌套列表,那么您可以试试这个

def find_index_of_max(nested_lst):
    _max, idx_path, cpath = None, None, []

    def find_max(lst, depth = 0):
        nonlocal idx_path, _max
        if len(cpath) - 1 < depth:
            cpath.append(0)

        for i, val in enumerate(lst):
            cpath[depth] = i
            if _max is None or val > _max:
                idx_path = tuple(cpath)
                _max = val
            elif isinstance(val, list):
                find_max(val, depth + 1)

    find_max(nested_lst)
    return idx_path

索引应该是
11
而不是
12
,因为python是零-indexed@James当前位置感兴趣的是12 OP的索引,而不是索引12.Ah。我明白你在说什么。“12的索引”有点含糊不清。我相信这会起作用,但我没有安装它,网站加载需要花费很长时间。经过更多的尝试,我发现如果最大的数字超过第三个索引,它将不会返回索引。我把[[1,1,1,1,9],[5,5,5,5,5]]放进去,它以(0,2)作为位置。
(2, 3)
(0, 4)
def find_index_of_max(nested_lst):
    _max, idx_path, cpath = None, None, []

    def find_max(lst, depth = 0):
        nonlocal idx_path, _max
        if len(cpath) - 1 < depth:
            cpath.append(0)

        for i, val in enumerate(lst):
            cpath[depth] = i
            if _max is None or val > _max:
                idx_path = tuple(cpath)
                _max = val
            elif isinstance(val, list):
                find_max(val, depth + 1)

    find_max(nested_lst)
    return idx_path
#Output
>>> find_index_of_max([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
(2, 3)
>>> find_index_of_max([[1,2,[16, [17, 18], 3], 3,4], [5,6,7,8], [9,10,11,12]])
(0, 2, 1, 1)