这是我的代码
a = [10,11,12]
index = [0,2]
print(a[index])
我希望10,12
作为输出,但会收到错误:
TypeError: list indices must be integers, not list
有可能在python中实现这样的东西吗?我知道我可以用列表理解来做,但想要更简单的东西。问题看起来如此pythonic。
答案 0 :(得分:5)
列表推导有什么问题?
In [1]: a = [10, 11, 12]
In [2]: indices = [0, 2]
In [3]: [a[i] for i in indices]
Out[3]: [10, 12]
答案 1 :(得分:3)
您可以使用operator.itemgetter
:
In [1]: from operator import itemgetter
In [2]: a = [10, 11, 12]
In [3]: index = [0, 2]
In [4]: itemgetter(*index)(a)
Out[4]: (10, 12)
答案 2 :(得分:1)
如果您需要特殊语义,可以创建一个列表子类:
class PickList(list):
def __getitem__(self, key):
return PickList([super(PickList, self).__getitem__(k) for k in key])
a = PickList([10,11,12])
index = [0, 2]
print a[index]