Python for-in 循环前面有一个变量
我看到一些代码,例如:
foo = [x for x in bar if x.occupants > 1]
这是什么意思,它是如何工作的?
I saw some code like:
foo = [x for x in bar if x.occupants > 1]
What does this mean, and how does it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当前的答案很好,但不要谈论它们如何只是语法糖到某种模式我们已经习惯了。
让我们从一个例子开始,假设我们有 10 个数字,并且我们想要大于 5 的数字的子集。
对于上述任务,下面的方法彼此完全相同,从最冗长到简洁、可读且Pythonic:
方法 1
方法 2(稍微简洁,for-in 循环)
方法 3(输入列表理解)
或更一般地说:
其中:
function(x)
接受一个x
并将其转换为有用的东西(例如:x*x
)condition(x )
返回任何 False-y 值(False、None、空字符串、空列表等),然后当前迭代将被跳过(认为继续
)。如果函数返回非 False-y 值,则当前值将进入最终结果数组(并经历上面的转换步骤)。要以稍微不同的方式理解语法,请查看下面的“奖励”部分。
有关更多信息,请按照所有其他答案链接的教程进行操作:列表理解
Bonus
(有点不符合Python风格,但为了完整起见把它放在这里)
上面的例子可以写成:
上面的一般表达式可以写成:
The current answers are good, but do not talk about how they are just syntactic sugar to some pattern that we are so used to.
Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.
For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and pythonic:
Approach 1
Approach 2 (Slightly cleaner, for-in loops)
Approach 3 (Enter List Comprehension)
or more generally:
where:
function(x)
takes anx
and transforms it into something useful (like for instance:x*x
)condition(x)
returns any False-y value (False, None, empty string, empty list, etc ..) then the current iteration will be skipped (thinkcontinue
). If the function return a non-False-y value then the current value makes it to the final resultant array (and goes through the transformation step above).To understand the syntax in a slightly different manner, look at the Bonus section below.
For further information, follow the tutorial all other answers have linked: List Comprehension
Bonus
(Slightly un-pythonic, but putting it here for sake of completeness)
The example above can be written as:
The general expression above can be written as:
这是一个 列表理解
foo
将是一个过滤后的bar
列表,其中包含具有属性 habitants > 的对象1bar
可以是list
、set
、dict
或任何其他可迭代对象 下面是一个示例来说明
So foo有 2 个
Bar
对象,但是我们如何检查它们是哪一个呢?让我们向Bar
添加一个__repr__
方法,以便提供更多信息It's a list comprehension
foo
will be a filtered list ofbar
containing the objects with the attribute occupants > 1bar
can be alist
,set
,dict
or any other iterableHere is an example to clarify
So foo has 2
Bar
objects, but how do we check which ones they are? Lets add a__repr__
method toBar
so it is more informative由于问题的编程部分已由其他人完全回答,因此很高兴了解它与数学的关系(集合论< /a>)。实际上它是Set 构建器表示法的 Python 实现:
因此,要使用 构建 B列表理解,B的成员(用x表示)是从集合A中选择的,其中
S(x ) == True
(包含条件)。注意:返回布尔值的函数
S
称为 predicate。Since the programming part of question is fully answered by others it is nice to know its relation to mathematics (set theory). Actually it is the Python implementation of Set builder notation:
So to build B with list comprehension, member(s) of B (denoted by x) are chosen from set A where
S(x) == True
(inclusion condition).Note: Function
S
which returns a boolean is called predicate.这将返回一个列表,其中包含 bar 中占用者 > 的所有元素。 1.
This return a list which contains all the elements in bar which have occupants > 1.
据我所知,它应该工作的方式是,它检查列表“bar”是否为空(0)或通过 x.occupants 由单例(1)组成,其中 x 是列表栏中定义的项目,可能具有居住者的特征。因此 foo 被调用,在列表中移动,然后返回所有通过检查条件(即 x.occupant)的项目。
在像 Java 这样的语言中,您可以构建一个名为“x”的类,然后将“x”对象分配给数组或类似的数组。 X 将有一个名为“占用者”的字段,并且将使用 x.ocupants 方法检查每个索引,该方法将返回分配给占用者的号码。如果该方法返回大于 1(我们假设这里的 int 作为部分占用者是奇怪的。) foo 方法(在数组或类似的问题上调用。)然后将返回一个数组或类似的数组,如 foo 方法中定义的那样对于这个容器数组或者你有什么。返回数组的元素将是第一个数组事物中符合“大于 1”条件的“x”对象。
Python 具有通过列表理解的内置方法,可以以更简洁和简化的方式处理此问题。我没有实现两个完整的类和多个方法,而是编写了一行代码。
The way this should work as far as I can tell is it checks to see if the list "bar" is empty (0) or consists of a singleton (1) via x.occupants where x is a defined item within the list bar and may have the characteristic of occupants. So foo gets called, moves through the list and then returns all items that pass the check condition which is x.occupant.
In a language like Java, you'd build a class called "x" where 'x' objects are then assigned to an array or similar. X would have a Field called "occupants" and each index would be checked with the x.occupants method which would return the number that is assigned to occupant. If that method returned greater than 1 (We assume an int here as a partial occupant would be odd.) the foo method (being called on the array or similar in question.) would then return an array or similar as defined in the foo method for this container array or what have you. The elements of the returned array would be the 'x' objects in the first array thingie that fit the criteria of "Greater than 1".
Python has built-in methods via list comprehension to deal with this in a much more succinct and vastly simplified way. Rather than implementing two full classes and several methods, I write that one line of code.