0

I have a list of tuples:
indices = [ (0,1) , (1,2) , (5,9) , ...] each tuple represent an index to be used with a list of lists representing a grid.

what I am doing to extract the actual values corresponding to the indices is:

for index in indices:
    x = grid [index[0]] [index[1]] # get the value and move on

Is there any better way to achieve this ? maybe something more "pythonic :D "

Thanks

3
  • Without knowing your application, the use of list of lists to create a grid sounds like you are missing numpy arrays. With an array you could, for example, use grid[zip(*indices)] and get all points you have in the indices, or just point by the tuples, e.g. grid[(5,9)]. Whether or not this is worth loading numpy depends on your application. If you do any maths, it is usually worth it. Commented Jun 15, 2014 at 20:56
  • yeah, I wish I could use numpy and avoid all this. Commented Jun 15, 2014 at 21:02
  • 1
    :) I know the feeling... However, as Cyber has shown below, there are a couple of alternatives depending on what you really want to do. Oh, and there is still the mickeymouse solution with you using a single list and doing the row/column arithmetics yourself. That may be the fastest solution, if you want to have speed. (Pythonic? Certainly not.) Commented Jun 15, 2014 at 21:29

1 Answer 1

1

You could use a list comp

[grid[x][y] for x, y in indices]

Or if you still need to do stuff once you get the value:

for x,y in indices:
    i = grid[x][y]
    # do stuff with i
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.