将Python列表理解理解为示例

问题描述 投票:0回答:2

我正在研究Python中的列表理解,并且遇到了以下示例:

vec = [[11, 21, 31],
[42, 52, 62],
[73, 83, 93]]
var=[vec[i][len(vec)-1-i] for i in range(len(vec))]
print(var)

我想确切地理解列表理解力所在行的逻辑,以及为什么代码停止迭代到i = 2? (我在调试模式下看到了,但是我仍然不清楚)。那么,“ len(vec)-1 -i是什么?我知道len(vec)-1是列表的最后一个,但是为什么-i?

python list-comprehension
2个回答
0
投票

我将逐步解释您的代码:

# This creates a 2D matrix (a nested list as we say in Python).
vec = [[11, 21, 31],
       [42, 52, 62],
       [73, 83, 93]]

# To obtain all the elements of the counterdiagonal in the 2D matrix, we iterate with inital value of i set to `0`, then,   
# Possible values for i varaible will be 0,1,2. 
# Hence, vec[i][len(vec)-1-i] will select following elements:
# vec[0][2] = 31
# vec[1][1] = 52
# vec[2][0] = 73
# These elements will then be stored in a new list named var. Hence when you print var, you'll get : 
var=[vec[i][len(vec)-1-i] for i in range(len(vec))]
# Output : [31, 52, 73]
print(var)

0
投票
var=[vec[i][len(vec)-1-i] for i in range(len(vec))]

此行表示列表理解。在这里,您正在为range(3)运行一个for循环,因此它在i=2处停止,依次迭代为012len(vec)-1 -i产生210。您正在通过for循环访问vec[0][2]vec[1][1],然后是vec[2][0]


0
投票

为什么代码停止迭代到i = 2? (我在调试模式下看到了,但对我来说仍然不清楚)

for i in range(len(vec))

什么是len(vec)vec是列表的列表。 len仅获得最外面的长度。在这种情况下,为3

尝试print(list(range(3))来查看将获得的i值。 (说明:range上限是互斥的,因此它将永远不会达到3。)

这可确保vec[i]永远不会超出范围。

那么,“ len(vec)-1 -i到底是什么?我知道len(vec)-1是我列表的最后一个,但是为什么-i?

vec[i][len(vec)-1-i]

vec[i]获取当前子列表。

[len(vec)是外部列表的长度(3),len(vec)-1是最后一个元素的索引,i从0到len(vec)-1(包括)

让我们分析每个[i]的len(vec)-1-i会得到什么值:

  • i = 0 => 2
  • i = 1 => 1
  • i = 2 => 0

我们基本上是在索引中“返回”。

所以我们得到vec[0][2]vec[1][1]vec[2][0]。也就是说,vec的对角线从右上到左下。

© www.soinside.com 2019 - 2024. All rights reserved.