admin管理员组

文章数量:1291423

Looking at prehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in prehensions in languages like Haskell.

Do they allow things like multiple generators? Or are they just a basic map-filter form?

If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?

Looking at prehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in prehensions in languages like Haskell.

Do they allow things like multiple generators? Or are they just a basic map-filter form?

If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?

Share Improve this question asked Oct 9, 2009 at 13:39 RD1RD1 3,32521 silver badges28 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 12

Python allows multiple generators:

>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5)]
[(1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4), 
 (2, 1, 2), (2, 2, 4), (2, 3, 6), (2, 4, 8), 
 (3, 1, 3), (3, 2, 6), (3, 3, 9), (3, 4, 12),
 (4, 1, 4), (4, 2, 8), (4, 3, 12), (4, 4, 16)]

And also restrictions:

>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5) if x*y > 8]
[(3, 3, 9), (3, 4, 12), (4, 3, 12), (4, 4, 16)]

Update: Javascript's syntax is similar (results from using the javascript shell on firefox):

var nums = [1, 2, 3, 21, 22, 30];
var s = eval('[[i,j] for each (i in nums) for each (j in [3,4]) if (i%2 == 0)]');
s.toSource();
[[2, 3], [2, 4], [22, 3], [22, 4], [30, 3], [30, 4]]

(For some reason, something about the context stuff is evaluated in in the javascript shell requires the eval indirection to have list prehensions work. Javascript inside a <script> tag doesn't require that, of course)

Yes, you can have multiple iterables in a Python list prehension:

>>> [(x,y) for x in range(2) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

Add an if statement as well...

>>> [(x,y) for x in range(5) for y in range(6) if x % 3 == 0 and y % 2 == 0]
[(0, 0), (0, 2), (0, 4), (3, 0), (3, 2), (3, 4)]

Comprehensions is very powerful in Haskell to a large extent because Haskell is functional, so it makes extremely much sense for them to be. Python is not functional so it makes less sense.

You can make a lot of plex things with prehensions in Python but it quickly bees hard to read, thereby defeating the whole purpose (meaning you should do it some other way).

However, as pointed out here, python does allow multiple generators in prehensions.

本文标签: Comprehensions in Python and Javascript are only very basicStack Overflow