Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using index() on multidimensional lists

Tags:

python

For a one dimensional list, the index of an item is found as follows:

 a_list = ['a', 'b', 'new', 'mpilgrim', 'new']
 a_list.index('mpilgrim')

What is the equivalent for a 2 or n dimensional list?

Edit: I have added an example to clarify: If I have a 3 dimensional list as follows

b_list = [
          [1,2],
          [3,4],
          [5,6],
          [7,8]
         ],
         [
          [5,2],
          [3,7],
          [6,6],
          [7,9]
         ]

Now lets say I want to identify a certain value in this list. If I know the index of the 1st and 2nd dimesion but don't know the zero-th index for the value I want, how do I go about finding the zero-th index?

Would it be something like:

  target_value = 7
  b_list[0].index(target_value)

With the output being an integer: 0

like image 983
Mandeep Avatar asked Jun 29 '11 09:06

Mandeep


People also ask

How is a 2D array indexed?

Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.

How do you access elements in a multidimensional array in python?

In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.

How do I iterate a two-dimensional list in python?

First, the list is assigned to a variable called data. Then we use a for loop to iterate through each element in the range of the list. Unless we specify a starting index for the range, it defaults to the first element of the list. This is index 0, and it's what we want in this case.


2 Answers

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)

like image 83
Rivka Avatar answered Oct 12 '22 07:10

Rivka


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
like image 31
utdemir Avatar answered Oct 12 '22 07:10

utdemir