1

In the following array, I want select a sub-array from array a when an id is known

a=[['id123','ddf',1],['id456','ddf',1],['id789','ddf',1]]

I know the id i.e, id456, based on this how can I select the values ['id456','ddf',1] from a without using any loop.

5
  • without using any loop. Is this homework? Commented Jun 4, 2012 at 12:58
  • definitively not an homework.. Commented Jun 4, 2012 at 12:58
  • What do you mean by no loop? As in no normal for loop? Are generator expressions like mine allowed? Commented Jun 4, 2012 at 12:59
  • this is a simple one ;) , just call it like you would any other list. a[0] should do the trick :) Commented Jun 4, 2012 at 13:00
  • 1
    If the list is sorted it should be possible to fetch a value in O(log n) time, but a loop of some sort (explicitly with a for loop or implicitly via more nuanced syntax) would still be required. You need a dictionary, or some other kind of mapping data structure, to do better. Commented Jun 4, 2012 at 13:05

5 Answers 5

2
>>> a = [['id123','ddf',1],['id456','ddf',1],['id789','ddf',1]]
>>> next(x for x in a if x[0] == 'id456')
['id456', 'ddf', 1]

I would however, recommend the use of a dictionary instead.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this should work...

filter(lambda x:x[0]=='id456',a)[0]

But in this case, wouldn't a dictionary be a better data structure?

2 Comments

That would still go through the entire list before it completes. And imo, a dictionary as you stated would be a better data structure to use.
@ChristianWitts This could work efficiently in Python 3 using next instead of [0] but as it is I agree that is inefficient and the use of lambda makes it ugly when compared to a generator expression.
0

A dictionary structure would work a lot better.

b = {'id123': ['ddf', 1], 'id456': ['dff', 1], 'id789': ['ddf', 1]}
print b['id123']

Comments

0

If the list is sorted, you can use the bisect module:

>>> i = bisect.bisect_left(a, ['id456'])
>>> if i < len(a) and a[i][0]=='id456':
...     print a[i]
...
['id456', 'ddf', 1]

Comments

0

You can use numpy.where() to do that:

a = numpy.array(a)

row = numpy.where(a == 'id456')[0]

sub_array = a[row,:]

This will check for elements with the desired id and give back their indexes. You can use these indexes to take slices from the original array, as the example shows.

This code will only work if there is a single row for the given ID, but it can be adapted.

Hope this helps.

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.