On 12/03/2015 10:27 AM, c.bu...@posteo.jp wrote:
I often saw constructions like this
x for x in y if ...
But I don't understand that combination of the Python keywords (for,
in, if) I allready know. It is to complex to imagine what there really
happen.
I understand this
for x in y:
if ...
But what is about the 'x' in front of all that?
I'd advise you insist on understanding this construct as it is a very
common (and useful) construct in python. It's a list comprehension, you
can google it to get some clues about it.
consider this example
[2*i for i in [0,1,2,3,4] if i%2] == [2,6]
you can split it in 3 parts:
1/ for i in [0,1,2,3,4]
2/ if i/2
3/ 2*i
1/ I'm assuming you understand this one
2/ this is the filter part
3/ this is the mapping part, it applies a function to each element
To go back to your question "what is about the 'x' in front of all
that". The x is the mapping part, but the function applied is the
function identity which simply keeps the element as is.
# map each element, no filter
[2*i for i in [0,1,2,3,4]] == [0, 2, 4, 6, 8]
# no mapping, keeping only odd elements
[i for i in [0,1,2,3,4] if i%2] == [1,3]
JM
--
https://mail.python.org/mailman/listinfo/python-list