为什么不能用索引列表索引python列表?

时间:2015-02-23 22:46:33

标签: python list

为什么python不允许这种语法:

l1 = range(1,6)
l2 = [0,3]
l1[l2]

我希望最后一行产生

[1,4]

我理解我可以使用列表推导(按照Getting a sublist of a Python list, with the given indices?)执行此操作,但我上面列出的语法似乎很自然,并且与np.arrays有效,我认为它们有在python中禁止它的一个很好的理由;它是什么?

1 个答案:

答案 0 :(得分:1)

Python不支持该语法,因为它不支持该语法。没有惹人注意的Guido van Rossum,这是你得到的最佳答案。

但是,添加到list子类很容易:

class List(list):
    def __getitem__(self, index):
        try:
            return list.__getitem__(self, index)
        except TypeError:
            return List(self[i] for i in index)
    def __setitem__(self, index, value):
        try:
            return list.__setitem__(self, index, value)
        except TypeError:
            value = iter(value)
            for i in index:
                self[i] = next(value)

a = List(range(10))
a.reverse()
print(a[1, 3, 5])    # [8, 6, 4]
a[1, 3, 5] = 1, 2, 3
print(a)             # [9, 1, 7, 2, 5, 3, 3, 2, 1, 0]

__setitem__如果你有更多的值而不是你正在填充的插槽(它可能会给你一个错误),那么表现不佳,但这也很棘手发电机,所以,meh。

实施它的微不足道可能与它不是语言的一部分有关; __getitem__尤其只是一个简单的列表理解(在这种情况下是生成器表达式),您可以在自己的代码中轻松编写,无论您需要在何处执行它。

相关问题