Home > Enterprise >  Find an index in a list of lists using an index inside one of the lists in pyton
Find an index in a list of lists using an index inside one of the lists in pyton

Time:01-15

I'm trying to determine if there is a way to access an index essentially by making a list of lists, where each inner list has a tuple that provides essentially grid coordinates, i.e:

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

and so on.

So, If I have coordinates (0,1), I want to be able to return example[1][0], or at the very least example[1] since these coordinates correlate with example[1].

I tried using index(), but this doesn't go deep enough. I also looked into itertools, but I cannot find a tool that finds it and doesn't return a boolean.

Using a number pad as an example:

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

I get an value error at the initiation of new_test.

CodePudding user response:

You can just yield from simple generator expression:

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

2

CodePudding user response:

You can create a function that will give you want

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

  • Related