Life is Really Short, Have Your Life!!

ござ先輩の主に技術的なメモ

Pythonでオブジェクトが入ってるリストをGroupbyして配列に分割する

こんなオブジェクトが格納されているリストがあるとします。

name age sex
foo 20 0
bar 30 1
hoge 40 0

それを性別で集計して各々別の配列に格納したい

作りたい配列はこんな感じ

i_want_such_a_list = [
   (0,(<foo,20,0>,<hoge,40,0>)),
   (1,(<bar,30,1>))
]

簡単に出来た

class SampleObj:

    name = ""
    sex = 0
    age = 0

    def __init__(self,name,sex,age):
        self.name= name
        self.sex= sex
        self.age = age

if __name__ == '__main__':
    sample = []
    sample.append(SampleObj(name='foo',sex=0,age=20))
    sample.append(SampleObj(name='bar',sex=1,age=30))
    sample.append(SampleObj(name='hoge',sex=0,age=20))

    import itertools
    sort_obj = sorted(sample, key=lambda x: x.age)
    group_by_sex = itertools.groupby(sort_obj, key=lambda x: x.age)
    for key, iter_obj in group_by_sex:
        print(key)
        for v in iter_obj:
            print(v.name)

PHPでも同じことは出来るんだろうけど、Pythonで書くとスッキリするわ...!!