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

查看:46
本文介绍了在 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天全站免登陆