I can't understand code with multi "for"s in one generator like this, I searched Google and didn't find any answer:
print [j for i in [[1,2],[4,6]] for j in i ]
# will print [1, 2, 4, 6]
print [j for j in i for i in [[1,2],[4,6]] ]
# will print [4, 4, 6, 6]
What is the difference?
How to interpret code like this?
Hopefully the expansions will help you reason with the code. It's a lot more readable this way, in my opinion. I'm printing one element at a time instead of the whole list.
print [j for i in [[1, 2], [4, 6]] for j in i]
is equivalent to
for i in [[1, 2], [4, 6]]:
for j in i:
print j
As a result i = [4, 6].
Now,
print [j for j in i for i in [[1,2],[4,6]]]
is equivalent to
for j in i: # Remember, i = [4, 6]
for i in [[1, 2], [4, 6]]:
print j
The second generater is error, but in your code scripts, the second generator, the i will be [4, 6] after your run the first generator, so the second will output [4, 4, 6, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With