Try this:
def index_2d(myList, v):
for i, x in enumerate(myList):
if v in x:
return (i, x.index(v))
Usage:
>>> index_2d(myList, 3)
(1, 0)
Answer from Mark Byers on Stack OverflowTry this:
def index_2d(myList, v):
for i, x in enumerate(myList):
if v in x:
return (i, x.index(v))
Usage:
>>> index_2d(myList, 3)
(1, 0)
If you are doing many lookups you could create a mapping.
>>> myList = [[1,2],[3,4],[5,6]]
>>> d = dict( (j,(x, y)) for x, i in enumerate(myList) for y, j in enumerate(i) )
>>> d
{1: (0, 0), 2: (0, 1), 3: (1, 0), 4: (1, 1), 5: (2, 0), 6: (2, 1)}
>>> d[3]
(1, 0)
An array and nested list version:
In [163]: A=np.arange(12).reshape(3,4)
In [164]: Al = A.tolist()
For sliced indexing, a list comprehension (or mapping equivalent) works fine:
In [165]: A[:,1:3]
Out[165]:
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])
In [166]: [l[1:3] for l in Al]
Out[166]: [[1, 2], [5, 6], [9, 10]]
For advanced indexing, the list requires a further level of iteration:
In [167]: A[:,[0,2,3]]
Out[167]:
array([[ 0, 2, 3],
[ 4, 6, 7],
[ 8, 10, 11]])
In [169]: [[l[i] for i in [0,2,3]] for l in Al]
Out[169]: [[0, 2, 3], [4, 6, 7], [8, 10, 11]]
Again there are various mapping alternatives.
In [171]: [operator.itemgetter(0,2,3)(l) for l in Al]
Out[171]: [(0, 2, 3), (4, 6, 7), (8, 10, 11)]
itemgetter uses tuple(obj[i] for i in items) to generate those tuples.
Curiously, itemgetter returns tuples for the list index, and lists for slices:
In [176]: [operator.itemgetter(slice(1,3))(l) for l in Al]
Out[176]: [[1, 2], [5, 6], [9, 10]]
Wasteful but should work:
list(zip(*(list(zip(*A))[0:9])))
Slightly more economical using itertools.isclice:
list(zip(*(itertools.islice(zip(*A), 0, 9))))
Or one could use map and operator.itemgetter:
list(map(operator.itemgetter(slice(0,9)), A))
arrays - How to get the full index of an object in a 2D list (Python) - Stack Overflow
Help finding the index of a given value within a 2D array
python - using index() on multidimensional lists - Stack Overflow
python - Indexing a 2D List with another List - Stack Overflow
Been messing around with numpy, trying to familiarize myself with it and seeing how I'd be able to utilize its arrays to store (very simple) map data for this text adventure game I've been working on. So far it seems like it'd be pretty darn useful, but I seem to have run into something of an issue.
My code is as follows (note: this is purposefully made with out a main class, because I am just trying to get the basic functionality down in my head before I incorporate it into my main program, and this is just easier for me):
# import numpy module as np
import numpy as np
# Establish the game map, a 3x3 grid of 0's
mainarray = np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
# Give feedback to make console easier to read
print(mainarray)
print("")
print("Placing player in center...")
# Place player on map (represented by a value of 1)
mainarray[1, 1] = 1
print(mainarray)
print("")
print("Locating player...")
# Attempt to find what the current index is of the value 1
print("")
print("Player is at index: ", np.where(mainarray == 1)[0][0])
In my head, I would like to eventually use this np.where() function (if I can) in one of the functions that moves my character. What I want to do is grab the current index of the "player" (represented by the number 1) and attempt to change that value to a 0, and change the value at an adjacent index to 1 (the tile that the player is moving to). Basically, I would like to use each index of the array as a sort of coordinate that I can take and use to move this "1" around the array, setting each index back to "0" after moving the "1", all based off user input.
Anyways, I am not getting any errors, however, the result that gets printed to the console is:
Player is at index: 1
Why is it just one number? It remains the same, even when I remove that second [0] in the last line. I don't fully understand how this function works, as this is the first time I've tried to use it, but since there are no errors, I have no clue what is going on.
Shouldn't I be receiving an index with two values, one for the column and one for the row? If not, how can I grab that as a result and use it in the way I described above? Is it even possible, or am I barking up the wrong tree with this function?
I don't know of an automatic way to do it, but if
a = [[1,2],[3,4],[5,6]]
and you want to find the location of 3, you can do:
x = [x for x in a if 3 in x][0]
print 'The index is (%d,%d)'%(a.index(x),x.index(3))
The output is:
The index is (1,0)
For two dimensional list; you can iterate over rows and using .index function for looking for item:
def find(l, elem):
for row, i in enumerate(l):
try:
column = i.index(elem)
except ValueError:
continue
return row, column
return -1
tl = [[1,2,3],[4,5,6],[7,8,9]]
print(find(tl, 6)) # (1,2)
print(find(tl, 1)) # (0,0)
print(find(tl, 9)) # (2,2)
print(find(tl, 12)) # -1
Since you're working with a 2D-list, it might be a good idea to use numpy. You'll then simply need to define index as a tuple. Index 3 would be out of range, though:
>>> import numpy as np
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> index = (1, 2)
>>> a[index]
6
The method you're looking for is called Array#dig in Ruby:
[[1,2,3], [4,5,6], [7,8,9]].dig(1, 2)
# 6
but I couldn't find any plain Python equivalent.
You could just create a simple function that iterates over the index. For every element in index just fetch item from object and assign that as a new object. Once you have iterated over the whole index return current object. As @EricDuminil noted it works with dicts and all other objects that support __getitem__:
def index(obj, idx):
for i in idx:
obj = obj[i]
return obj
LST = [[1,2,3], [4,[5],6], [{'foo': {'bar': 'foobar'}},8,9]]
INDEXES = [[2, 2], [1, 1, 0], [2, 0, 'foo', 'bar']]
for i in INDEXES:
print('{0} -> {1}'.format(i, index(LST, i)))
Output:
[2, 2] -> 9
[1, 1, 0] -> 5
[2, 0, 'foo', 'bar'] -> foobar
With list comprehension:
>>> [(r, c) for r, line in enumerate(two_d_list) for c, num in enumerate(line) if num==1]
[(0, 1), (1, 0), (1, 1), (2, 3)]
two_d_list = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1]]
result = []
for i in range(len(two_d_list)):
for j in range(len(two_d_list[i])):
if two_d_list[i][j] == 1:
result.append((i, j))
print(result)
Result:
[(0, 1), (1, 0), (1, 1), (2, 3)]
Assuming you don't want to reinvent the wheel I believe this question has the answer you're looking for: Is there a Numpy function to return the first index of something in an array?
import numpy as np
a = np.array([[1,2,4],[4,5,6]])
item = 4
row_indices, col_indices = np.where(a == item)
Try something like this.
>>> l = [[1,2,3],[4,5],[6,7,8,9]]
>>> x = 1
>>> y = 2
>>> v = l[x][y] if len(l) > x and len(l[x]) > y else None
>>> v is None
True