Access multiple elements of list knowing their index

hoang tran :

I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]

Is there any better way to do it? something like c = a[b] ?

TerryA :

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It's probably the neatest out of all of them.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Index of multiple minimum elements in a list

Python: access multiple elements in list

Splitting list into multiple lists - depending on elements index

Remove multiple elements from a list of index with Python

Find index for multiple elements in a long list

Delete multiple elements in a list by index in Python

How to add multiple elements in a list together by index?

Set vs List when need both unique elements and access by index

How do I access elements in a list by index in DAML?

UnboundLocalError when trying to delete multiple list elements by index

How to display the index for multiple elements with same value in an array list

How to access child elements without knowing the parent in firebase realtime database?

access elements of dataframes in list?

Access to list elements in R

Access elements of a list in a yaml

access elements in list of lists

Python given dict of old index: new index move multiple elements in a list

Access JavaScript object elements by index

Access struct elements via index

Is there another way to print multiple list elements where the list index increases by a given amount with each print?

If -multiple- elements are not in a list, then

How to construct list comprehension, needing to access multiple elements in list during each iteration?

Searching for the index of certain elements in a list of list of list

Access dict keys and list elements by same index to loop over and assign values

Prelude.!!: index too large (Haskell recursion based on access to previously calculated list elements.)

finding the index of elements in nested list

Duplicate elements of a list on even index

Delete dict elements by index list

Deleting elements in a list by their value as index

TOP Ranking

HotTag

Archive