Python split a list into subsets based on pattern

前端 未结 3 1157
名媛妹妹
名媛妹妹 2021-01-02 06:31

I\'m doing this but it feels this can be achieved with much less code. It is Python after all. Starting with a list, I split that list into subsets based on a string prefix.

3条回答
  •  余生分开走
    2021-01-02 06:52

    Use itertools' groupby:

    def get_field_sub(x): return x.split('_')[1]
    
    mylist = sorted(mylist, key=get_field_sub)
    [ (x, list(y)) for x, y in groupby(mylist, get_field_sub)]
    

提交回复
热议问题