繁体   English   中英

在python中,如何基于键(组相邻)将元素组合在一起?

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

python ,我想基于一个键将元素组合在一起(在下面的例子中,key是第二个元素,或者element[1] )。

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

只有哪些键相同且相邻的元素才应组合在一起。

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

另外,我希望导致拆分的元素也位于前一个数组的末尾。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM