是否可以使用python中的元组索引嵌套列表?

Aod*_*oss 5 python tuples nested-lists

我刚开始使用python,很快就想知道是否可以使用元组索引嵌套列表.就像是:elements[(1,1)]

我想要做的一个例子类似于下面的代码,我在其中保存矩阵的一些位置,我稍后需要在一个名为index的元组中访问它.

index = ( (0,0), (0,2), (2,0), (2,2) )

elements = [ [ 'a', 'b', 'c'],
             [ 'c', 'd', 'e'],
             [ 'f', 'g', 'h'] ]

for i in index:
    print (elements [ i[0] ] [ i[1] ])

    # I would like to do this:
    # print(elements[i])
Run Code Online (Sandbox Code Playgroud)

这似乎是一个有用的功能.这有什么办法吗?或者也许是一个简单的选择

Ran*_*niz 7

如果你真的想使用元组进行索引,你可以实现自己的类扩展list和重新定义__getattr__以使用元组并使用它:

class TList(list):
    def __getitem__(self, index):
        if hasattr(index, "__iter__"):
            # index is list-like, traverse downwards
            item = self
            for i in index:
                item = item[i]
            return item
        # index is not list-like, let list.__getitem__ handle it
        return super().__getitem__(index)

elements = TList([ [ 'a', 'b', 'c'],
                   [ 'c', 'd', 'e'],
                   [ 'f', 'g', 'h'] ])
index = ( (0,0), (0,2), (2,0), (2,2) )
for i in index:
    print(elements[i])
Run Code Online (Sandbox Code Playgroud)

一个
Ç
˚F
ħ


Rya*_*yan 2

是的,你可以这么做。我写了一个类似的例子:

index = [ [0,0], [0,2], [2,0], [2,2] ]

elements = [ [ 'a', 'b', 'c'],
             [ 'c', 'd', 'e'],
             [ 'f', 'g', 'h'] ]

for i,j in index:
    print (elements [ i ] [ j ])
Run Code Online (Sandbox Code Playgroud)

ACFH