Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
synthax question
#1
Hi,

I have a long experience in computing but not in python. I need to understand this :

combinableLayers=[l for l in combinableLayers if len(l)>1 ]

I have of course found what is a list, what is a for loop but impossible to understand this line, especially " l for l .."

Can someone please help me ?

Thanks && regards

aka
Reply
#2
Take a look at what those pythonistas call "list comprehension" :-)

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
Written as normal for loop.
combinableLayers = ([0, 1, 2], [9], [7, 8])
new_lst = []
for l in combinableLayers:
    if len(l) > 1:
        new_lst.append(l)

print(new_lst)
Output:
[[0, 1, 2], [7, 8]]
In Python list comprehension is a common and alternative syntax to make it in one expression.
combinableLayers = ([0, 1, 2], [9], [7, 8])
combinableLayers = [l for l in combinableLayers if len(l) > 1]
print(combinableLayers)
Output:
[[0, 1, 2], [7, 8]]
BashBedlam likes this post
Reply
#4
Thanks, I reached the first step. For the second one, take please a look :

combinableLayers=[[l for l in g.layers if l.visible] for g in image.layers if g.visible and isinstance(g,gimp.GroupLayer)]

I found some help searching "nested list comprehension" but it is here not enought, I see 'g' in the inner and the outer list.

Is it the same 'g', is it a "correled nested list comprehension" ? How does that work ? I please need to be sure. :)

I attached the whole script (see too https://www.gimp-forum.net/Thread-ofn-ex...mbinations).

Attached Files

.py   ofn-export-layers-combinations.py (Size: 3.39 KB / Downloads: 103)
Reply
#5
combinableLayers=[[l for l in g.layers if l.visible] for g in image.layers if g.visible and isinstance(g,gimp.GroupLayer)]
Quote:I see 'g' in the inner and the outer list.
Is it the same 'g', is it a "correled nested list comprehension" ? How does that work ?
The g is local to list comprehension,what's take in for outside is image.layers then both do a test against this image.layers.
The code in ofn-export-layers-combinations.py is written in Python 2 in 2021,which is outdated as support for Python 2 officially stopped January 1 2020.
BashBedlam likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020