The previous post I've talked about tricky list comprehension:
>>> ll = [[1,2,3], [4,5,6], [7,8]]
>>> l = [i for j in l for i in j]
>>> print l
... [1, 2, 3, 4, 5, 6, 7, 8]
But there are another pretty interesting solution for this task. It's based on built-in sum function:
>>> sum(ll)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Not working... But sum has optional param called `start` (which is 0 by default). So we could pass empty list, so every element in ll will be +'ed to it:
>>> print sum(ll, [])
... [1, 2, 3, 4, 5, 6, 7, 8]
Hooray! It works! And it's elegant. ;)
>>> ll = [[1,2,3], [4,5,6], [7,8]]
>>> l = [i for j in l for i in j]
>>> print l
... [1, 2, 3, 4, 5, 6, 7, 8]
But there are another pretty interesting solution for this task. It's based on built-in sum function:
>>> sum(ll)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Not working... But sum has optional param called `start` (which is 0 by default). So we could pass empty list, so every element in ll will be +'ed to it:
>>> print sum(ll, [])
... [1, 2, 3, 4, 5, 6, 7, 8]
Hooray! It works! And it's elegant. ;)
No comments:
Post a Comment