[Python] coding help -- iterating over 2 arrays by individual orderings

Bob Miller kbob at jogger-egg.com
Thu Jan 11 23:39:15 PST 2007


Bob Miller wrote:

>    t_order = [(item.seq, 'a', item.content) for item in text]
>    m_order = [(item.seq, 'b', item.content) for item in media]
>    for seq, content in t_order + m_order:
> 	display_text_or_media(content)

D'oh!  The third line was supposed to read,

    for seq, content in sorted(t_order + m_order):

Sorry...

Actually, you could use sorted()'s key argument to simplify that.

    for content in sorted(text + media, key=lambda item: item.seq):
        display_text_or_media(content)

Is that not Pythonic enough for you? (-:  Perhaps this is.

    from itertools import chain
    for content in sorted(chain(text, media), key=lambda i: i.seq):
        display_text_or_media(content)

-- 
Bob Miller                              K<bob>
                                        kbob at jogger-egg.com


More information about the Python mailing list