Statement (un)equality

A

Adam Przybyla

castle:/home/adam>python
Python 2.3 (#3, Aug 4 2003, 16:43:33)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
[[y,x] for x,y in [1,2],[3,4]] [[2, 1], [4, 3]]
map(lambda x,y: [y,x], [1,2],[3,4]) [[3, 1], [4, 2]]
Why there is a difference? How to make the same thing like in map statement?
Regards
Adam Przybyla
 
J

Jonas Galvez

[Adam Przybyla]
[[y,x] for x,y in [1,2],[3,4]] [[2, 1], [4, 3]]
map(lambda x,y: [y,x], [1,2],[3,4])
[[3, 1], [4, 2]]
def test(a,b):
print "a:", a, "b:", b
return [b,a]
a: 1 b: 3
a: 2 b: 4
[[3, 1], [4, 2]]
[test(a, b) for a, b in [1,2], [3,4]]
a: 1 b: 2
a: 3 b: 4
[[2, 1], [4, 3]]
[test(a, b) for a, b in zip([1,2], [3,4])]
a: 1 b: 3
a: 2 b: 4
[[3, 1], [4, 2]]



Jonas
 
E

Erik Max Francis

Adam said:
[[y,x] for x,y in [1,2],[3,4]] [[2, 1], [4, 3]]
map(lambda x,y: [y,x], [1,2],[3,4]) [[3, 1], [4, 2]]
Why there is a difference? How to make the same thing like in map
statement?

Because the same things aren't happening here, despite their outward
similarity. For the second case to be equivalent to the first, you
really meant:
map(lambda x: [x[1], x[0]], [[1, 2], [3, 4]])
[[2, 1], [4, 3]]

You can pass multiple sequences to map, and that interleaves the
results:
map(lambda x, y, z: (x, y, z), [1, 2], [3, 4], [5, 6])
[(1, 3, 5), (2, 4, 6)]
 
J

James Henderson

castle:/home/adam>python
Python 2.3 (#3, Aug 4 2003, 16:43:33)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
[[y,x] for x,y in [1,2],[3,4]]

[[2, 1], [4, 3]]
map(lambda x,y: [y,x], [1,2],[3,4])

[[3, 1], [4, 2]]

Why there is a difference?

Hi,

[[y,x] for x,y in [1,2],[3,4]]

is just the same as:

[[y,x] for (x,y) in ([1,2],[3,4])]

The list comprehension regards "[1,2],[3,4]" as a single argument (a tuple)
and "x,y" is also a tuple. "x,y" is assigned first [1,2] and then [3,4].

In the map statement "[1,2],[3,4]" are two different arguments. map's
signature allows for any number of iterables to be passed after the first
argument.
How to make the same thing like in map
statement?

zip() gives you the sequence of pairs you want to pass: (zip() is very
similar to map with None as the first arguemnt. The difference is how they
handle sequences of unequal length.)
[(1, 3), (2, 4)]

so:

[[y,x] for x,y in zip([1,2],[3,4])]

will match the behaviour of the map statement.
Regards
Adam Przybyla

James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,078
Latest member
MakersCBDBlood

Latest Threads

Top