Group list by values

后端 未结 7 1616
说谎
说谎 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:48

    I don't know about elegant, but it's certainly doable:

    oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
    # change into: list = [["A", "C"], ["B"], ["D", "E"]]
    
    order=[]
    dic=dict()
    for value,key in oldlist:
      try:
        dic[key].append(value)
      except KeyError:
        order.append(key)
        dic[key]=[value]
    newlist=map(dic.get, order)
    
    print newlist
    

    This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.

提交回复
热议问题