[英]Finding the index of the maximum value of nested lists 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.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的解決方案將是(假設列表及其第一個元素永遠不會為空):
def maxIndex(nestedList):
m = (0,0)
for i in range(len(nestedList)):
for j in range(len(nestedList[i])):
if nestedList[i][j] > nestedList[m[0]][m[1]]:
m = (i,j)
return m
mylist1 = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
mylist2 = [[1,1,1,1,9], [5,5,5,5,5]]
def myfunc(mylist):
xx = mylist.index(max(mylist, key = lambda x:max(x)))
yy = mylist[xx].index(max(mylist[xx]))
print(xx,yy)
myfunc(mylist1)
myfunc(mylist2)
退貨
(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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.