2017-03-03 27 views
-2

2D列表中查找索引我需要找到索引中的2D陣列,其中的數量是任一比編號,以左,右和小於上面和下面,或反之亦然的數字越大。在用條件

我知道我需要兩個for循環一個用於行第一列,我給了數字x,我需要將它與2d數組中的數字進行比較以查找索引。

list = [[1,4,6,7,8], 
     [2,4,6,7,8], 
     [1,4,6,7,8], 
     [1,4,6,7,8], 
     [2,4,6,7,8], 
     [6,4,6,7,8]] 

如果我給4爲x,我需要找到索引在2D列表,向左,向右,向上和向下,反之亦然其他數大於或小於4,可有人請提供一個解決方案

list = [[1, 4, 6, 7, 8], 
     [2, 4, 6, 7, 8], 
     [1, 4, 6, 7, 8], 
     [1, 4, 6, 7, 8], 
     [2, 4, 6, 7, 8], 
     [6, 4, 6, 7, 8]] 

x = [x for x in list if 4 in x][0] 
print('The index is (%d,%d)' % (list.index(x), x.index(4))) 

隨着企圖只會給我的第一指標,但我需要檢查整個數組,並使用一個if語句來檢查大於小於的問題。

+5

不是家庭作業服務,通過嘗試解決方案讓我們半途而廢。 – ospahiu

+0

嘗試加入的問題 – mcfellows

回答

0

這會做...

x = int(input('Enter x: ')) 
data = [[1, 4, 6, 7, 8], 
     [2, 4, 6, 7, 8], 
     [1, 4, 6, 7, 8], 
     [1, 4, 6, 7, 8], 
     [2, 4, 6, 7, 8], 
     [6, 4, 6, 7, 8]] 

dataTranspose = list(zip(*data)) 

for each_row_number in range(0, len(data)): 

    tempRow = list(enumerate(data[each_row_number])) 
    maxIndex, maxVal = max(tempRow, key=lambda eachPair: eachPair[1]) 
    minIndex, minVal = min(tempRow, key=lambda eachPair: eachPair[1]) 

    if x == maxVal: 
     if x == min(dataTranspose[maxIndex]): 
      print(' found another at: (' + str(each_row_number) + ', ' + str(maxIndex) + ')') 
    elif x == minVal: 
     if x == max(dataTranspose[minIndex]): 
      print(' found another at: (' + str(each_row_number) + ', ' + str(minIndex) + ')') 

實例運行:

Enter x: 8 
found another at: (0, 4) 
found another at: (1, 4) 
found another at: (2, 4) 
found another at: (3, 4) 
found another at: (4, 4) 
found another at: (5, 4) 

實例運行:

Enter x: 4 
found another at: (5, 1) 

實例運行:

Enter x: 6 

(在第三個例子中沒有結果,對於x = 6,給定條件中的任何一個都不滿足第二個列表中的任何地方)。

+0

非常感謝tkhurana96看起來是差不多就是我要找的 – mcfellows

+0

@mcfellows巨大的,如果它是有幫助的你 – tkhurana96