Group list by values

后端 未结 7 1603
说谎
说谎 2020-12-01 03:09

Let\'s say I have a list like this:

mylist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]

7条回答
  •  隐瞒了意图╮
    2020-12-01 03:47

    >>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
    >>> xs.sort(key=lambda x: x[1])
    >>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
    [[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]
    

    Basically, if the list is sorted, it is possible to reduce by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l bit is a trick that enables us to use lambda in Python. (append returns None. It is always better to return something more useful than None, but, alas, such is Python.)

提交回复
热议问题