Retrieving Multiple Elements from a List Based on Known Indices
To extract specific elements from a list knowing their indices, you can employ the following methods:
1. List Comprehension:
As you already demonstrated, list comprehensions provide a concise way to extract elements according to indices:
a = [-2, 1, 5, 3, 8, 5, 6] b = [1, 2, 5] c = [a[i] for i in b]
2. operator.itemgetter:
The itemgetter operator from the operator module allows you to retrieve elements based on a sequence of indices:
from operator import itemgetter a = [-2, 1, 5, 3, 8, 5, 6] b = [1, 2, 5] print(itemgetter(*b)(a)) # Result: (1, 5, 5)
3. Numpy (if available):
If you have Numpy installed, you can leverage its array indexing capabilities:
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]
While all three methods can accomplish the task, the list comprehension approach is generally considered the most readable and concise. However, if you value speed or efficiency, itemgetter or Numpy might offer better performance.
以上是如何根据已知索引从列表中提取元素?的详细内容。更多信息请关注PHP中文网其他相关文章!