CoffeeScript list comprehensions are slightly different from Pythons... which of these is the way that people like to return list comprehensions?
return elem+1 for elem in [1,2,3] # returns 3+1
return [elem+1 for elem in [1,2,3]].pop() #开发者_如何学Python returns [2,3,4]
return (elem+1 for elem in [1,2,3]) # returns [2,3,4]
In Python, I would just write:
return [elem+1 for elem in [1,2,3]]
And it returns the list correctly, instead of a list of lists, as this would do in CoffeeScript.
Which of these is the way that people like to return list comprehensions?
return elem+1 for elem in [1,2,3] # returns 3+1
return [elem+1 for elem in [1,2,3]].pop() # returns [2,3,4]
return (elem+1 for elem in [1,2,3]) # returns [2,3,4]
Well, of the three options, certainly #3. But the best stylistic choice is actually this:
elem+1 for elem in [1,2,3] # returns [2,3,4]
As the last line of a function, any expression expr
is equivalent to return (expr)
. The return
keyword is very rarely necessary.
I've never used CoffeeScript, but if my options were getting the wrong result, doing a silly [...].pop()
kludge or just using a set of parenthesis, I'd go for the parenthesis.
精彩评论