帮助 python 列表理解
我的问题的简化版本:
我有一个列表理解,我用它在二维列表上设置位标志,所以:
s = FLAG1 | FLAG2 | FLAG3
[[c.set_state(s) for c in row] for row in self.__map]
所有 set_state 所做的是:
self.state |= f
这工作正常,但我必须在 __map 中的每个单元格中都有这个函数“set_state”。 __map 中的每个单元格都有一个 .state,所以我想做的是:
[[c.state |= s for c in row] for row in self.map]
或
map(lambda c: c.state |= s, [c for c in row for row in self.__map])
两者都不起作用(语法错误)。也许我用map/lamda找错了树,但我想摆脱set_state。也许知道为什么赋值在列表理解中不起作用
A simplified version of my problem:
I have a list comprehension that i use to set bitflags on a two dimensional list so:
s = FLAG1 | FLAG2 | FLAG3
[[c.set_state(s) for c in row] for row in self.__map]
All set_state does is:
self.state |= f
This works fine but I have to have this function "set_state" in every cell in __map. Every cell in __map has a .state so what I'm trying to do is something like:
[[c.state |= s for c in row] for row in self.map]
or
map(lambda c: c.state |= s, [c for c in row for row in self.__map])
Except that neither works (Syntax error). Perhaps I'm barking up the wrong tree with map/lamda but I would like to get rid on set_state. And perhaps know why assignment does not work in the list-comprehension
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
列表推导式用于创建列表。您似乎并不关心您正在创建的实际列表,因此您应该只使用
for
语句,如下所示:List comprehensions are for creating lists. You don't seem to care about the actual lists you are making, so you should just use a
for
statement, like so:是的,您使用了错误的工具。列表理解返回一个全新的值,因此您也许可以这样做:
但我的直觉是您应该只使用两个 for 循环:
在列表理解中,结果必须是一个表达式。那是因为你的双重理解只是糖:
说
因为最里面的表达式必须返回要附加到
list2
的内容是没有意义的。基本上,每次更新标志时,列表推导都会生成 self.__map 的完整新副本。如果这就是你想要的,那就随它去吧。但我怀疑你只是想改变现有的地图。在这种情况下,请使用双
for
循环。Yes, you're using the wrong tool. A list comprehension returns a completely new value, so you might be able to do this:
But my instinct is that you should just be using two for loops:
In a list comprehension, the result has to be an expression. That's because your double comprehension is just sugar for this:
It makes no sense to say
Because the innermost expression has to return something to be appended to
list2
.Basically, the list comprehensions make a complete new copy of self.__map each time you update the flags. If that's what you want, then go with it. But I suspect you just want to change the existing map. In that case, use the double
for
loops.您不需要列表理解,因为您正在就地修改数据,而不是创建新列表。
做一个循环。
You don't want a list comprehension, since you're modifying your data in-place, not creating a new list.
Do a loop.
使用
setattr
函数:然后阅读关于无语句Python。
Use the
setattr
function:And then read up on Statementless Python.
在 python 中,赋值是语句,而不是表达式,仅在 lambda 中允许和列表理解。
In python assignments are statements, not expressions which are only allowed in lambdas and list comprehension.