python列表元素分组,Python:如何将类似的列表分组到一个列表列表中?

I have a list of lists in python. I want to group similar lists together. That is, if first three elements of each list are the same then those three lists should go in one group. For eg

[["a", "b", "c", 1, 2],

["d", "f", "g", 8, 9],

["a", "b", "c", 3, 4],

["d","f", "g", 3, 4],

["a", "b", "c", 5, 6]]

I want this to look like

[[["a", "b", "c", 1, 2],

["a", "b", "c", 5, 6],

["a", "b", "c", 3, 4]],

[["d","f", "g", 3, 4],

["d", "f", "g", 8, 9]]]

I could do this by running an iterator and manually comparing each element of two consecutive lists and then based on the no of elements within those lists that were same I can decide to group them together. But i was just wondering if there is any other way or a pythonic way to do this.

解决方案>>> A=[["a", "b", "c", 1, 2],

... ["d", "f", "g", 8, 9],

... ["a", "b", "c", 3, 4],

... ["d","f", "g", 3, 4],

... ["a", "b", "c", 5, 6]]

>>> from operator import itemgetter

>>> [list(g) for _,g in groupby(sorted(A),itemgetter(0,1,2)]

[[['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 3, 4], ['a', 'b', 'c', 5, 6]], [['d', 'f', 'g', 3, 4], ['d', 'f', 'g', 8, 9]]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值