reduce to be removed?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Nov 12 03:14:59 CET 2006


On Sat, 11 Nov 2006 17:42:32 -0800, Dustan wrote:

>> alright, let's try again: why do you need a self-contained reduce
>> replacement that can be embedded inside a list comprehension ?
>>
>> </F>
> 
> 
>>>> foo =\
> [[[1,2,3],[4,5,6],[7,8,9]],
>  [[3,2,1],[6,5,4],[9,8,7]]]
> 
> Here, foo appears to be a 3-dimensional list - except it's supposed to
> be 2-dimensional. The inner-list-of-lists is a result of how I'm
> producing the data, and now I want to do a mass-concatenation (or
> extending) of the inner-list-of-lists, and come up with this result:
> 
>>>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
> True
> 
> What's the best way to accomplish this?

I don't know if this is the best, but it didn't take long to come up with
it:

>>> foo = [[[1,2,3],[4,5,6],[7,8,9]],
... [[3,2,1],[6,5,4],[9,8,7]]]
>>>
>>> def unroll(list3d):
...     newl = []
...     for sublist in list3d:
...             newl.append(sum(sublist, []))
...     return newl
...
>>> bar = unroll(foo)
>>> bar
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]]


Repeat after me: 

"Not everything has to be a one-liner."


If sum() is too slow, because your sub-lists are huge, you can easily
factor that out and replace it with something using extend.


-- 
Steven.




More information about the Python-list mailing list