python嵌套列表推导 [英] python nested list comprehensions

查看:56
本文介绍了python嵌套列表推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python并阅读其教程.我了解列表理解和嵌套列表理解.但是,通过下面的代码,我试图了解事件的顺序.

I am learning python and going through their tutorials. I understand list comprehensions and nested lists comprehensions. With the following code, though, I am trying to understand the order of events.

>>> matrix = [
...[1, 2, 3, 4],
...[5, 6, 7, 8],
...[9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4,8,12]]

根据嵌套列表的理解,第一个"i"和第二个"i"是否是相同的变量,并且它们都同时增加吗?我想我不明白结果大列表如何从第一个子列表[1,5,9]转到第二个子列表[2,6,10]

According to the nested list comprehension, is the first "i" and the second "i" the same variable and do they both increase at the same time? I guess I don't understand how the resulting big list goes from the first sublist [1, 5, 9] to the second sublist [2, 6, 10]

推荐答案

[[row[i] for row in matrix] for i in range(4)]

等同于

my_list = []
for i in range(4):
    my_list_2 = []
    for row in matrix:
        my_list_2.append(row[i])
    my_list.append(my_list_2)


第一个"i"和第二个"i"是相同的变量,并且它们都同时增加吗?

is the first "i" and the second "i" the same variable and do they both increase at the same time?

当然可以.如果它不是相同的 i ,则该代码将引发错误,因为将不会定义两者之一.

Of course, it is. If it was not the same i, the code would throw an error because one of the two would not be defined.

您可能对此问题感兴趣:了解嵌套列表的理解

You may be interested in this question: Understanding nested list comprehension

这篇关于python嵌套列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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