簡體   English   中英

使用 pyton 中的一個列表中的索引在列表列表中查找索引

[英]Find an index in a list of lists using an index inside one of the lists in pyton

我試圖確定是否有一種方法可以通過創建列表列表來訪問索引,其中每個內部列表都有一個提供基本網格坐標的元組,即:

example = [
     ['a', (0,0)], ['b',(0,1)], ['c', (0,2)],
     ['d', (1,0)], ['e',(1,1)], ['d', (1,2)],
     .....
     ]

等等。

因此,如果我有坐標(0,1) ,我希望能夠返回example[1][0] ,或者至少返回example[1] ,因為這些坐標與example[1]相關。

我嘗試使用index() ,但這 go 不夠深。 我也查看了 itertools,但我找不到找到它並且不返回 boolean 的工具。

以數字鍵盤為例:

from itertools import chain
def pinpad_test():
   pad=[
      ['1',(0,0)],['2',(0,1)],['3',(0,2)],
      ['4',(1,0)],['5',(1,1)],['6',(1,2)],
      ['7',(2,0)],['8',(2,1)],['9',(2,2)],
      ['0',(3,1)]
      ]
   tester = '1234'
   print(tester)
   for dig in tester:
      print(dig)
      if dig in chain(*pad):
         print(f'Digit {dig} in pad')
      else:
         print('Failed')
      print('end of tester')
   new_test = pad.index((0,1)in chain(*pad))
   print(new_test)

if __name__ == '__main__':
   pinpad_test()

我在new_test開始時收到一個值錯誤。

您可以從簡單的生成器表達式中產生:

coords = (0, 1)
idx = next((sub_l[0] for sub_l in pad if sub_l[1] == coords), None)
print(idx) 

2

您可以創建一個 function 來滿足您的需求

def on_coordinates(coordinates:tuple, list_coordinates:list):
    return next(x for x in list_coordinatesif x[1] == coordinates)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM