是否可以在python中使用元组索引嵌套列表? [英] Is it possible to index nested lists using tuples in python?

查看:635
本文介绍了是否可以在python中使用元组索引嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just started with python and very soon wondered if indexing a nested list with a tuple was possible. Something like: elements[(1,1)]

我要执行此操作的一个示例与下面的代码相似,其中我保存了矩阵的某些位置,以后需要在称为索引的元组中访问该矩阵的位置.

One example where I wanted to do that was something similar to the code below in which I save some positions of the matrix that I will later need to access in a tuple called 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])

这似乎是一个有用的功能.有什么办法吗?还是一个简单的替代方法?

It seems like a useful feature. Is there any way of doing it? Or perhaps a simple alternative?

推荐答案

是的,您可以这样做.我写了一个类似的例子:

Yes, you can do that. I wrote a similar example:

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 ])

a c f h

a c f h

这篇关于是否可以在python中使用元组索引嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆