Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: filtering lists by indices

In Python I have a list of elements aList and a list of indices myIndices. Is there any way I can retrieve all at once those items in aList having as indices the values in myIndices?

Example:

>>> aList = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> myIndices = [0, 3, 4] >>> aList.A_FUNCTION(myIndices) ['a', 'd', 'e'] 
like image 493
Ricky Robinson Avatar asked Aug 07 '12 13:08

Ricky Robinson


People also ask

How do you filter a list by condition in Python?

The most straightforward and beginner-friendly approach to filtering a list is by using a for loop: A for loop goes through each element of a list. It checks if an element satisfies a condition. Based on the condition it adds the element to the result.

How do you filter a list of words in Python?

filter() method is a very useful method of Python. One or more data values can be filtered from any string or list or dictionary in Python by using filter() method. It filters data based on any particular condition. It stores data when the condition returns true and discard data when returns false.

Do Python lists have indices?

python lists are 0-indexed. So the first element is 0, second is 1, so on. So if the there are n elements in a list, the last element is n-1.

How do you filter a list?

Select a cell in the data table. On the Data tab of the Ribbon, in the Sort & Filter group, click Advanced, to open the Advanced Filter dialog box. For Action, select Filter the list, in-place.


1 Answers

I don't know any method to do it. But you could use a list comprehension:

>>> [aList[i] for i in myIndices] 
like image 58
Valdir Stumm Junior Avatar answered Sep 23 '22 16:09

Valdir Stumm Junior