在Python中将列表推导转换为For循环 [英] Converting List Comprehensions to For Loops in Python

查看:212
本文介绍了在Python中将列表推导转换为For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解列表理解的重要性,但不了解它们的内部工作原理,因此无法以简单的术语(例如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 lists (and other iterables).

这篇关于在Python中将列表推导转换为For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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