亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

滄海一幻覺 2021-08-11 22:43:18
從輸入導入列表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))這并沒有真正起作用,因為它只是返回該數字不在列表中
查看完整描述

3 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您還可以充分利用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]

輸出


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

# [1, 0]

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

# [2, 2]


查看完整回答
反對 回復 2021-08-11
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

我認為當您考慮迭代索引而不是列表中的項目時它更容易:


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)


查看完整回答
反對 回復 2021-08-11
?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

您可以在展平的輸入結構中找到最大值,然后返回指定先前找到的最大值位置的坐標:


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]]])))

輸出:


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


查看完整回答
反對 回復 2021-08-11
  • 3 回答
  • 0 關注
  • 422 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號