Find a specific element in a list with sub-lists (Python)

Asked

Viewed 535 times

0

I’m tweaking a Pathfindig code based on A*,

I need to check and modify an element within a list with several sub-lists, but I have doubts if I use a repeat loop, or if there is already a function that does this, (Return as value the position of this element in the list).

V = 3, 3 # V equivale ao elemento[0] de cada sub-lista.
lista = [[[1,3] 2,1 , 40, 90], [[2,3] 3,2 , 60, 50], [[3,3] 4,2 , 70, 15]...]

As I can for example check if V is in the list and if I was, how can I change it. Thanks in advance!

  • What language ? Python ?

  • Ops forgot that detail, yes it’s python.

  • What would those be [1,3], [2,3] and [3,3]? Didn’t make much sense.

  • In my code they are coordinates of a map (initially of characters), where each element of the list is a position, with its information. (In this example I put random values in these coordinates because it is just an example,)

  • But V is a tuple whereas [3,3] is a list with two elements

1 answer

2


If I understand what you want to do, then maybe it’s better to use a dictionary with position tuples as keys:

>>> posicoes = {(1, 3): [2, 1, 40, 90], (2, 3): [3, 2, 60, 50]}
>>> posicoes[3, 3] = [4, 2, 70, 15]
>>> print(posicoes)
{(1, 3): [2, 1, 40, 90], (2, 3): [3, 2, 60, 50], (3, 3): [4, 2, 70, 15]}
>>> (3, 3) in posicoes
True
>>> posicoes[3, 3]
[4, 2, 70, 15]
>>> posicoes[3, 3][2] = 80
>>> posicoes[3, 3]
[4, 2, 80, 15]
  • With dictionary I’m better, vlw ae.

  • What if, for example, I want to access the third element of this dictionary, in the same way as lists? type position[2] accesses the third element... of course in dictionary it doesn’t work that way, but there is some way?

  • @Marcosvinícius common dictionaries do not guarantee to keep the insertion order. If you want to guarantee this, you will have to use a OrderedDict (from collections import OrderedDict and then is instantiating and use normally, only instantiating as posicoes = OrderedDict()). Hence, you can make list(positions.values()[2] to access the 3rd element value (or posicoes.items() to access a tuple with key and value, or posicoes.keys() to access only the key).

  • Dear Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.