In python, how to group elements together, based on a key (group adjacent)?

前端 未结 1 817
一整个雨季
一整个雨季 2021-01-20 08:30

In python, I\'d like to group elements together based on a key (in example below, key is second element, or element[1]).

initial_a         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 09:08

    You can use itertools.groupby:

    >>> from itertools import groupby
    >>> from operator import itemgetter
    >>> lis = [[10, 0], [30, 0], [40, 2], [20, 2], [90, 0], [80, 0]]
    >>> [list(g) for k,g in groupby(lis, key=itemgetter(1))]
    [[[10, 0], [30, 0]],
     [[40, 2], [20, 2]],
     [[90, 0], [80, 0]]]
    

    For second one:

    >>> ans = []
    for k,g in groupby(lis, key=itemgetter(1)):
        l = list(g)
        ans.append(l)
        if len(ans) > 1:
            ans[-2].append(l[0])
    ...         
    >>> ans
    [[[10, 0], [30, 0], [40, 2]],
     [[40, 2], [20, 2], [90, 0]],
     [[90, 0], [80, 0]]]
    

    Update:

    >>> from itertools import zip_longest
    >>> lis = [[[10, 0], [30, 0]],
     [[40, 2], [20, 2]],
     [[90, 0], [80, 0]]]
    >>> [x + ([y[0]] if y else []) for x,y in 
                                            zip_longest(lis,lis[1:])]
    [[[10, 0], [30, 0], [40, 2]],
     [[40, 2], [20, 2], [90, 0]],
     [[90, 0], [80, 0]]]
    

    0 讨论(0)
提交回复
热议问题