简体   繁体   中英

Get list of items based on indices from list of indices

I have a list called a . I have a list of indices called b .

How do I set all the elements of a with indices in b to 0 ?

In other languages I could do a[b] = 0 , this returns the error TypeError: list indices must be integers or slices, not list , I am not sure what the efficient pythonic way of accomplishing this is.

Both a and b may be fairly large.

#we are given this:
a = [2,4,6,8,10,12,14,16,18,20]#some list
b = [2,3,6,9]#some set of indices

#we aim to get this:
c = [6,8,14,20]

Edit to provide a sample code.

I am answering this question based on some of the comments, as it was at the time locked due to me being unclear and not providing an example.

We can get c as required by either using list comprehension :

#Solution 1, use list comprehension
c = [a[i] for i in b]
print(c)

or numpy:

#Solution 2, convert to numpy
a = np.array(a)
c = a[b]
print(c.tolist())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM