如何基于谓词将列表划分为较小列表的列表? [英] How to divide a list into a list of smaller lists based on a predicate?

查看:32
本文介绍了如何基于谓词将列表划分为较小列表的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的列表:

Let's say I have a list like this:

[('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]

我想将其转换为这样的列表:

And I'd like to convert it to a list like this:

[ [('Yadda', 5), ('Yadda', 9)], [('Blah', 12), ('Blah', 2), ('Blah', 4)] ]

假设列表是根据谓词进行排序的,则对它进行排序-

Assuming the list is sorted wrt the predicate on which it should be split -

使用Python的方式是什么?

What's the Pythonic way of doing this?

是否有执行此操作的功能,或者我必须自己编写?

Is there any function that does this or do I have to write it myself?

推荐答案

您可以使用 itertools.groupby .

from itertools import groupby

l = [('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]

l.sort(key=lambda item: item[0])

result = [list(group) for _, group in groupby(l, key=lambda item: item[0])]

这篇关于如何基于谓词将列表划分为较小列表的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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