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 badges4 Answers
Reset to default 12Python 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
版权声明:本文标题:Comprehensions in Python and Javascript are only very basic? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741519697a2383106.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论