Python split a list into subsets based on pattern

前端 未结 3 1022
名媛妹妹
名媛妹妹 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:56

    In [28]: mylist = ['sub_0_a', 'sub_0_b', 'sub_1_a', 'sub_1_b']
    
    In [29]: lis=[]
    
    In [30]: for x in mylist:
        i=x.split("_")[1]
        try:
            lis[int(i)].append(x)
        except:    
            lis.append([])
            lis[-1].append(x)
       ....:         
    
    In [31]: lis
    Out[31]: [['sub_0_a', 'sub_0_b'], ['sub_1_a', 'sub_1_b']]
    

提交回复
热议问题