unzipの一般化

30分プログラム、その410。http://d.hatena.ne.jp/hiloicoli/20081107/1226086092に影響を受けてunzip_nを書いてみる。

要するに任意個の引数を取れるunzipといった感じらしい。もとは引数の数を制限できるようになっていたけど、大変そうなのでパス。

>>> unzip_n([(1,'one','-'),(2,'two','--'),(3,'three','---')])
[[1, 2, 3], ['one', 'two', 'three'], ['-', '--', '---']]

ところで、これってRubyだとArray#transposeと同じ挙動だったりする。まさか行列の転地とunzipが継がるとは。

使い方

>>> unzip_n([(1,'one','-'),(2,'two','--'),(3,'three','---')])
[[1, 2, 3], ['one', 'two', 'three'], ['-', '--', '---']]

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# unzipn.py -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/11/10 22:41:11
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def unzip2(xs):
    ys = []
    zs = []
    for (y,z) in xs:
        ys.append(y)
        zs.append(z)
    return (ys,zs)

def unzip_n(xs):
    unziped = map(lambda x: [x],xs[0])
    for item in xs[1:]:
        map(lambda x,y: x.append(y),unziped,item)
    return unziped

print unzip_n([(1,'one','-'),
               (2,'two','--'),
               (3,'three','---')])