Python list help

A simplified version of my problem:

I have an understanding of the list, which I use to set bit flags in 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 value:

self.state |= f

This works fine, but I have to have this set_state function in every cell in __map. Each cell in __map has a .state, so I'm trying to do 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 it does not work (syntax error). I may bark the wrong tree with map / lamda, but I would like to get rid of set_state. And perhaps you know why the assignment does not work in list comprehension

+3
source share
5 answers

, . , :

self.__map = [[c.state | s for c in row] for row in self.__map]

, :

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.

, , self.__ map. , , . , . for.

+3

. , , , for, :

for row in self.__map:
    for c in row:
        c.state |= s
+4

You do not need to understand the list because you are modifying your data in place, rather than creating a new list.

Do a loop.

+1
source

Use function setattr:

setattr(c, "state", s)

And then read Carefree Python .

0
source

Python assignments use expressions, not expressions that are only allowed in lambdas and understand the list.

0
source

Source: https://habr.com/ru/post/1740452/


All Articles