interleaving dictionary values
Roberto Bonvallet
Roberto.Bonvallet at cern.ch
Tue Nov 21 10:18:12 EST 2006
j1o1h1n at gmail.com wrote:
[...]
> I had in mind something like this:
>
>>>> interleave([1, 2, 3], [4,5], [7, 8, 9])
> [1, 4, 7, 2, 5, 8, 3, 9]
[...]
> But instead I (finally worked out I could) do this:
>
> apply(map, tuple([None] + d.values()))
apply is deprecated, it should be map(None, *d.values())
> So... my bit of code becomes:
>
> filter(None, flatten(map(None, apply(map, tuple([None] +
> d.values())))))
>
> It fits on one line, but it feels far more evil than I set out to be.
> The brackets at the end are bad for my epilepsy.
>
> Surely there is there some nice builtin function I have missed?
You have missed the "it doesn't need to be a one-liner" motto :)
>>> def interleave(*args):
... result = []
... for items in map(None, *args):
... result.extend([x for x in items if x is not None])
... return result
...
>>> interleave([1, 2, 3], [4,5], [7, 8, 9])
[1, 4, 7, 2, 5, 8, 3, 9]
Cheers,
--
Roberto Bonvallet
More information about the Python-list
mailing list