Python podzielił listę na podzbiory na podstawie wzorca

Robię to, ale wydaje się, że można to osiągnąć za pomocą znacznie mniejszej ilości kodu. W końcu to Python. Począwszy od listy, dzielę tę listę na podzbiory na podstawie prefiksu łańcucha.

# Splitting a list into subsets
# expected outcome:
# [['sub_0_a', 'sub_0_b'], ['sub_1_a', 'sub_1_b']]

mylist = ['sub_0_a', 'sub_0_b', 'sub_1_a', 'sub_1_b']

def func(l, newlist=[], index=0):
    newlist.append([i for i in l if i.startswith('sub_%s' % index)])
    # create a new list without the items in newlist
    l = [i for i in l if i not in newlist[index]]

    if len(l):
        index += 1
        func(l, newlist, index)

func(mylist)

questionAnswers(3)

yourAnswerToTheQuestion