在python中,如何基于键(相邻组)将元素分组在一起? [英] In python, how to group elements together, based on a key (group adjacent)?

查看:163
本文介绍了在python中,如何基于键(相邻组)将元素分组在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中,我想基于一个键将元素分组在一起(在下面的示例中,键是第二个元素或element[1]).

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

initial_array = [[10, 0], [30, 0], [40, 2], [20, 2], [90, 0], [80, 0]]

只有键相同且相邻的元素才应该组合在一起.

Only elements which keys are the same and that are adjacent should be grouped together.

splited_array = [ [[10, 0], [30, 0]], 
                  [[40, 2], [20, 2]], 
                  [[90, 0], [80, 0]] ]

此外,我希望引起拆分的元素也位于上一个数组的末尾.

Additionally, i'd like the element that caused the split to be also at the end of the previous array.

splited_array = [ [[10, 0], [30, 0], [40, 2]], 
                  [[40, 2], [20, 2], [90, 0]], 
                  [[90, 0], [80, 0]] ]

在python中最简单的方法是什么? (如果可能,请重新使用内置函数)

What is the easiest way to do that in python ? (re-using Built-in Functions if possible)

推荐答案

您可以使用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]]]

第二个:

>>> 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]]]

更新:

>>> 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]]]

这篇关于在python中,如何基于键(相邻组)将元素分组在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆