Why does this list comprehension not do what I expect from it?

The initial list project_keys = sorted(projects.keys())is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]where the following projects were considered invalidthis year: 108, 109, 110.

In this way:

for project in projects.itervalues():
# The projects dictionary is mapped to the Project class
    if project.invalid:
    # Where invalid is a Bool parameter in the Project class
     project_keys.remove(project.proj_id)  

print project_keys

This will return a list of integers (which are project identifiers) as such:

[101, 102, 103, 104, 105, 106, 107]

Sweet.

Now I wanted him to try to do the same, using list comprehension.

project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid  

print project_keys

This returns:

[None, None, None]

So, I populate the list with the same number as the deleted items, but are they Nones?

Can someone point out what I'm doing wrong?

Also, why should I use list comprehension above the block for-ifat the top? Laconicism? Looks better?

+3
source share
2

. , project_keys, .

[project_keys.remove(project.proj_id)
 for project in projects.itervalues()
 if project.invalid]

remove None. project_keys , .

, , . , , .

:

project_keys = sorted(project.proj_id
                      for project in projects.itervalues()
                      if not project.invalid)

, , , , . , .

+6

, , .

, , ( )

.

project_keys = [project_keys.remove(project.proj_id)
                for project in projects.itervalues() if project.invalid]

dummy = []
for project in projects.itervalues():
  if project.invalid:
    dummy.append(project_keys.remove(project.proj_id)) #what are you
project_keys = dummy                                   #removing items from?
del dummy                                            

( "" )

mapped-fun = lambda project: project_keys.remove(project.proj_id)
filtering-fun = lambda project: project.invalid
project_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues()))

, for. , map() filter(): , , .

, , . , " " , , list.sort(); , sorted().

, "", , ; , . , , , , ?

., , , , project_keys, , !

, . .


, , , .

( )

, (= .)

dummy = []
for project in projects.itervalues():
  if not project.invalid:
    dummy.append(project.proj_id)
project_keys = dummy
del dummy

, ( )

mapped-fun = lambda project: project.proj_id
filtering-fun = lambda project: not project.invalid
project_keys = map(mapped-fun, filter(filtering-fun, projects.itervalues()))

, ( )

project_keys = [project.proj_id for project in projects.itervalues()
                if not project.invalid]
+4

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


All Articles