Well, I was looking on the site and I didn't find anything that could help me, so I came to ask. How do I get items from a list if its index is on another list ?
Example:
I have an array of vectors:
[[0.0,0.0,0.1] [0.4,0.23,0.175] [0.0,1.,0.5] [0.0,0.03,0.1] [0.02,0.0,0.3]]
and a list of indices:
[0,2,3]
I want a result like this:
[[0.0,0.0,0.1] [0.0,1.,0.5] [0.0,0.03,0.1]]
how can I get this result? Grateful for any help :)
something like this
lst1 = [[0.0, 0.0, 0.1], [0.4, 0.23, 0.175], [0.0, 1., 0.5], [0.0, 0.03, 0.1], [0.02, 0.0, 0.3]]
lst2 = [0, 2, 3]
lst3 = [x for idx, x in enumerate(lst1) if idx in lst2]
print(lst3)
output
[[0.0, 0.0, 0.1], [0.0, 1.0, 0.5], [0.0, 0.03, 0.1]]
You can do this with a list comprehension.
For example:
mylist = [[0.0,0.0,0.1], [0.4,0.23,0.175], [0.0,1.,0.5], [0.0,0.03,0.1], [0.02,0.0,0.3]]
indices = [0,2,3]
result = [mylist[i] for i in indices]
result is now [[0.0, 0.0, 0.1], [0.0, 1.0, 0.5], [0.0, 0.03, 0.1]]
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.