从2D python列表中拉出某些元素?

Max*_*Max 1 python testing list

作为一种简单的方法来测试拉出大型tileset的某些元素的正确方法,在我的程序中作为2D列表输入,我将以下内容放入Python Shell:

->>>test = [ [1,2,3],[4,5,6],[7,8,9] ]
Run Code Online (Sandbox Code Playgroud)

在试图测试它时,我得到了这个:

->>>test1 = test[:][2]

->>>test1

[7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

从输入test[:][2]我预期的test1到返回[3,6,9]

有人可以向我解释为什么我会这样做[7,8,9]吗?

另外,如果你能解释我将如何获得输出[3,6,9]?我知道我可以说以下内容:

>>>test1 = [ test[0][2], test[1][2], test[2][2] ]
Run Code Online (Sandbox Code Playgroud)

但如果我在我的程序环境中编写它,那条线就会更长,更难维护.如果有一种[3,6,9]比我上面列出的方式更容易获得的方式,我将非常感谢有关获得它的一些见解.

Rom*_*kar 5

对于标准python,你可以这样做:

>>> test = [[1,2,3],[4,5,6],[7,8,9]]
>>> [x[2] for x in test]
[3, 6, 9]
>>> 
Run Code Online (Sandbox Code Playgroud)

至于test1 = test[:][2],因为test[:]只是等于test(编辑: 实际上,它是精确的副本test而不是相同的列表)

还看看numpy图书馆.

  • 更具体地说,`test [:]`是`test`的*copy*,而不仅仅是一个引用...例如,如果你做了'a = test`,`a`和`test`仍然会引用相同的列表,但是`a = test [:]`,`a`和`test`现在引用不同的列表. (2认同)