我的问题的简化版本:
我有一个列表理解,我用它来设置二维列表上的位标记,所以:
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 |= fThis 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
最满意答案
是的,你正在使用错误的工具。 列表理解返回一个全新的值,所以你可以这样做:
self.__map = [[c.state | s for c in row] for row in self.__map]但我的直觉是你应该只使用两个for循环:
for row in self.__map: for c in row: c.state |= s在列表理解中,结果必须是表达式。 那是因为你的双重理解只是为了这个糖:
list1 = [] for row in self.__map: list2 = [] for c in row: list2.append(c.state | s) list1.append(list2) self.__map = list1说没有意义
list2.append(c.state |= s)因为最里面的表达式必须返回要附加到list2 。
基本上,每次更新标志时,列表解析都会创建自我.__映射的完整新副本。 如果这就是你想要的,那就去吧。 但我怀疑你只是想改变现有的地图。 在这种情况下,使用double for循环。
Yes, you're using the wrong tool. A list comprehension returns a completely new value, so you might be able to do this:
self.__map = [[c.state | s for c in row] for row in self.__map]But my instinct is that you should just be using two for loops:
for row in self.__map: for c in row: c.state |= sIn a list comprehension, the result has to be an expression. That's because your double comprehension is just sugar for this:
list1 = [] for row in self.__map: list2 = [] for c in row: list2.append(c.state | s) list1.append(list2) self.__map = list1It makes no sense to say
list2.append(c.state |= s)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.
更多推荐
发布评论