iterating quickly through list of tuples

前端 未结 5 1692
清歌不尽
清歌不尽 2020-12-05 06:34

I wonder whether there\'s a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is:

# this is a very lon         


        
5条回答
  •  余生分开走
    2020-12-05 07:10

    I wonder whether the below method is what you want.

    You can use defaultdict.

    >>> from collections import defaultdict
    >>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
    >>> d = defaultdict(list)
    >>> for k, v in s:
           d[k].append(v)    
    >>> sorted(d.items())
    [('blue', [2, 4, 4]), ('red', [1, 3, 1])]
    

提交回复
热议问题