我需要从给定列表中选择一些元素,知道它们的索引。假设我想创建一个新列表,其中包含索引为1,2,5的元素,来自给定列表[-2,1,5,3,8,5,6]。我做的是:a = [-2,1,5,3,8,5,6]b = [1,2,5]c = [ a[i] for i in b]有没有更好的方法呢?像c = a [b]之类的东西?
4 回答

收到一只叮咚
TA贡献1821条经验 获得超4个赞
你可以使用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)
或者你可以使用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]
但实际上,您当前的解决方案很好。它可能是所有这些中最好的。

浮云间
TA贡献1829条经验 获得超4个赞
备择方案:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)

繁花如伊
TA贡献2012条经验 获得超12个赞
另一种解决方案可能是通过熊猫系列:
import pandas as pd
a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]
然后,您可以根据需要将c转换回列表:
c = list(c)
添加回答
举报
0/150
提交
取消