2

I have a simple program:

pos = [1,2]
searched = [
    [1,3,4,6],
    [2,6,7,8],
    [0,1,2,8],
    [5,6,9,2]
]
print(searched[pos[0]][pos[1]])
7

Now what I want is some way to get rid off of searched[pos[0]][pos[1]] and just type something like searched[[pos]].

Is there a way to this, or do I have to write out this every time

I have gotten a lot of suggestions, but what I am searching for is a way to do this in one neat line, simplifying everything.
That means that things like using a function, converting to a specific dictionary or even enumerate don't work for me, so for anyone looking at this post later:
.
I suggest using np.array(variable) while defining said variable so you can use variable[pos]

Sadru
  • 46
  • 1
  • 9

5 Answers5

2

Don't know if this is acceptable to you, but a function will do:

def search_for_list_item_by_index(a_list, row, col):
    return a_list[row][col]

print(search_for_list_item_by_index(searched, 1, 2))

This prints 7, as expected.

asymmetryFan
  • 712
  • 1
  • 10
  • 18
2

You can do this by converting your array to numpy as suggested by @oppressionslayer. One other way to do that is to create a dictionary and use that as follows:

pos = [1,2]
searched = [
    [1,3,4,6],
    [2,6,7,8],
    [0,1,2,8],
    [5,6,9,2]
]
m=4 # width of the searched array
n=4 # hight of the searched array

searched = {(i,j):searched[i][j] for j in range(m) for i in range(n)}

print(searched[1,2]) # prints 7
print(searched[tuple(pos)]) # prints 7

Hope this helps!!

HNMN3
  • 542
  • 3
  • 9
1

You can convert this to a numpy array and get the search your looking for:

import numpy as np
pos = [1,2] 
searched = np.array([ 
  [1,3,4,6], 
  [2,6,7,8], 
  [0,1,2,8], 
  [5,6,9,2] 
  ]) 
print(searched[1,2])  
# 7
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
1

You can use the following function:

def func(idx, lst):
    for i in idx:
        lst = lst[i]
    return lst

func(pos, searched)
# 7
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
0

I'd use the dictionary approach like HNMN3 but what is fun is you can generalize to non rectangular lists by using enumerate:

searched = {(row,col):item
              for row,elems in enumerate(searched)
                for col,item in enumerate(elems)}

or use flatten_data from my answer here which does the same thing but works for totally arbitrary nesting including dictionaries. Probably not the direction you want but worth mentioning.

data = flatten_data(searched)
pos = [1,2]
print(data[1,2])
print(data[tuple(pos)])
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59