问题描述
我了解列表理解的重要性,但不了解它们的内部工作原理,因此无法以简单的术语(例如for循环)来理解它们.例如,如何将其更改为for循环:
I understand the importance of list comprehensions, but do not understand their inner-workings, thus am not able to understand them in simpler terms such as I would a for loop. For example, how could I change this to a for loop:
li = [row[index] for row in outer_list]
在此示例中,我有一个列表列表,出于我的目的,我们使用一个名为 outer_list 的矩阵,它是一个列表列表. index 值是外部迭代所在的列号,从0到某个数字n.上面的列表理解返回矩阵中的第 index 列,并将其分配给 li 作为列表.如何创建一个以这种方式创建列表的for循环?
In this example I have a list of lists, for my purposes a matrix, called outer_list which is a list of lists. The index value is the column number the outer iteration is at, from 0 to some number n. The list comprehension above returns the index'th column in the matrix, and assigns it to li as a list. How can I create a for loop that creates a list in this manner?
推荐答案
这只是表达list
的一种较短方法.
It's just a shorter way of expressing a list
.
li = [row[index] for row in outer_list]
等效于:
li = []
for row in outer_list:
li.append(row[index])
一旦习惯了语法,它就会成为创建list
(和其他可迭代对象)的一种整洁方式.
Once you get used to the syntax, it becomes a tidy way of creating list
s (and other iterables).
这篇关于在Python中将列表推导转换为For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!