这个"[.... in ..]"如何进行?在Python中工作? [英] How does this "[.. for .. in ..]" work in Python?

查看:81
本文介绍了这个"[.... in ..]"如何进行?在Python中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我,它是如何工作的?为什么每次迭代结果都写入数组?

Tell me please, how does it work exactly? Why does each iteration result write to array?

list_of_strings = [a.rstrip('\n') for a in list_of_strings]

推荐答案

这将获取一个字符串列表(存储在变量list_of_strings中),对其进行迭代,每次通过时将每个字符串临时分配给变量a并剥离每个字符串中的\n字符.结果是分配给相同变量的字符串的 list .

This takes a list of strings (stored in variable list_of_strings), iterates through it assigning each string temporarily to variable a each time through and strips the \n character from each string. The result is a list of strings that is assigned back to the same variable.

这是使用列表理解.通常,大多数涉及append()的for循环和列表操作都可以转换为等效的列表理解.这是一个简单的例子,证明了这一点:

This is using List Comprehension. Generally most for-loops and list operations involving append() can be converted to equivalent list comprehensions. Here's a simple example demonstrating this:

   new_list = []
   for i in range(10):
       new_list.append(i**2)

可以简单地重写为

   new_list = [i**2 for i in range(10)]

进行列表理解并用for循环将其重写以测试您的理解可能会很有帮助(两者都应产生相同的结果).

You may find it instructive to take your list comprehension and rewrite it with a for-loop to test your understanding (both should produce identical results).

在大多数情况下,列表理解比等效的for循环要快,并且显然是一种更紧凑的算法表达方式.您也可以嵌套列表推导(就像您可以嵌套for -loops一样),但是它们很快就会变得难以理解:)

In most cases, list comprehension is faster than the equivalent for-loop and clearly a more compact way to express an algorithm. You can have nested list comprehensions too (just as you can have nested for-loops), but they can quickly become hard to comprehend :)

此外,虽然上面的代码中未显示,但您可以过滤列表理解中的值,即根据它们是否满足某些条件,将它们包括(或不包括)在结果列表中.

Also, while not shown in the code above, you can filter values in the list comprehension, i.e., including them (or not) in the resulting list depending on whether they meet some criteria.

顺便说一句,Python还提供了类似的集合理解和生成器表达式.值得学习所有这些.

As an aside, Python also provides similar set comprehensions and generator expressions. It's well worth learning about all of these.

这篇关于这个"[.... in ..]"如何进行?在Python中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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