Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python finding index of an array within a list

Tags:

python

numpy

What I have is a list where the elements are an array like this:

([1,2,3],[4,5,6],[7,8,9])

What I want is to find the index of an element in this list, something like:

list.index([4,5,6]) #should return 1.

Problem is numpy array comparison throws up errors unless you put something like: (A==B).all()

But this comparison is inside the index function so i can't and don't really want to add the all() bit to the function. Is there an easier solution to this?

like image 778
Mad Program Avatar asked Oct 18 '25 23:10

Mad Program


2 Answers

Your last error message indicates that you are still mixing lists and arrays. I'll try to recreate the situation:

Make a list of lists. Finding a sublist works just fine:

In [256]: ll=[[1,2,3],[4,5,6],[7,8,9]]
In [257]: ll.index([4,5,6])
Out[257]: 1

Make an array from it - it's 2d.

In [258]: la=np.array(ll)
In [259]: la
Out[259]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

It does not have an index method

In [260]: la.index([4,5,6])
...
AttributeError: 'numpy.ndarray' object has no attribute 'index'

Make it a list - but we get your ValueError:

In [265]: list(la).index([4,5,6])
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

That's because list(la) returns a list of arrays, and arrays produce multiple values in == expressions:

In [266]: list(la)
Out[266]: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

The correct way to produce a list from an array is tolist, which returns the original ll list of lists:

In [267]: la.tolist().index([4,5,6])
Out[267]: 1
like image 74
hpaulj Avatar answered Oct 20 '25 13:10

hpaulj


If you are starting with a numpy array, you can get the result that you want by converting it to a list of lists before using the index() function, e.g.:

import numpy as np

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
lst = [list(x) for x in arr]
print (lst.index([4,5,6]))

... which gives the expected output 1.

like image 35
Simon Avatar answered Oct 20 '25 12:10

Simon