itertools.groupby() 是做啥用的?

     2023-02-23     28

关键词:

【中文标题】itertools.groupby() 是做啥用的?【英文标题】:What is itertools.groupby() used for?itertools.groupby() 是做什么用的? 【发布时间】:2017-05-15 15:43:37 【问题描述】:

在阅读 python 文档时,我遇到了itertools.groupby() 功能。这不是很简单,所以我决定在 *** 上查找一些信息。我从How do I use Python's itertools.groupby()? 找到了一些东西。

这里和文档中似乎很少有关于它的信息,所以我决定发布我对 cme​​ts 的观察。

谢谢

【问题讨论】:

你检查grouby() document了吗?哪一部分不直截了当? @MoinuddinQuadri OP的问题的第一句话说他们阅读了Python文档。 您提出的问题已准备好详尽的答案?真的吗?为什么不在问题中包含所有这些,而将答案部分留给讨论? @hiroprotagonist It's perfectly acceptable to ask a question for the sole purpose of answering it。我自己做过。 “为什么不在问题中包含所有内容”因为答案不是问题的一部分。答案就是答案。 @EmettSpeer 我的实际问题是“这其中哪一部分不是直截了当的?”。我提到文档的链接只是为了确保 OP 检查了官方 Python 文档,而不是任何教程 【参考方案1】:

与往常一样,documentation of the function 应该是第一个要检查的地方。然而itertools.groupby 肯定是最棘手的itertools 之一,因为它有一些可能的陷阱:

如果它们的key-result 对于连续的项目是相同的,它只会对项目进行分组:

from itertools import groupby

for key, group in groupby([1,1,1,1,5,1,1,1,1,4]):
    print(key, list(group))
# 1 [1, 1, 1, 1]
# 5 [5]
# 1 [1, 1, 1, 1]
# 4 [4]

之前可以使用sorted - 如果想要整体使用groupby

它产生两个项目,第二个是一个迭代器(所以需要迭代第二个项目!)。在前面的示例中,我明确需要将这些转换为 list

如果推进groupby-iterator,则丢弃第二个产生的元素:

it = groupby([1,1,1,1,5,1,1,1,1,4])
key1, group1 = next(it)
key2, group2 = next(it)
print(key1, list(group1))
# 1 []

即使group1 不为空!

正如已经提到的,可以使用sorted 进行整体groupby 操作,但效率极低(如果您想在生成器上使用 groupby,则会丢弃内存效率)。如果您不能保证输入是 sorted(也不需要 O(n log(n)) 排序时间开销),还有更好的选择:

collections.defaultdict iteration_utilities.groupedby 可能更多。

但是,检查本地属性非常棒。 itertools-recipes section里有两个菜谱:

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

和:

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return map(next, map(itemgetter(1), groupby(iterable, key)))

【讨论】:

谢谢。如果我需要一些替代品,我一定会注意的。现在我正在逐节阅读文档,以免混淆所有内容。祝你新年快乐 这里有很棒的信息。 collections.defaultdict 的文档有一个关于如何对值进行分组的非常简单的示例:docs.python.org/3/library/collections.html#defaultdict-examples【参考方案2】:

首先,您可以阅读文档here。

我将把我认为最重要的一点放在首位。我希望通过示例后原因会变得清晰。

始终使用用于分组的相同键对项目进行排序以避免意外结果

itertools.groupby(iterable, key=None or some func) 获取可迭代的列表并根据指定的键对它们进行分组。键指定对每个单独的迭代应用什么操作,然后将其结果用作每个项目分组的标题;最终具有相同“键”值的项目将最终在同一组中。

返回值是一个类似于字典的可迭代对象,其格式为key : value

示例 1

# note here that the tuple counts as one item in this list. I did not
# specify any key, so each item in the list is a key on its own.
c = groupby(['goat', 'dog', 'cow', 1, 1, 2, 3, 11, 10, ('persons', 'man', 'woman')])
dic = 
for k, v in c:
    dic[k] = list(v)
dic

结果

1: [1, 1],
 'goat': ['goat'],
 3: [3],
 'cow': ['cow'],
 ('persons', 'man', 'woman'): [('persons', 'man', 'woman')],
 10: [10],
 11: [11],
 2: [2],
 'dog': ['dog']

示例 2

# notice here that mulato and camel don't show up. only the last element with a certain key shows up, like replacing earlier result
# the last result for c actually wipes out two previous results.

list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \
               'wombat', 'mongoose', 'malloo', 'camel']
c = groupby(list_things, key=lambda x: x[0])
dic = 
for k, v in c:
    dic[k] = list(v)
dic

结果

'c': ['camel'],
 'd': ['dog', 'donkey'],
 'g': ['goat'],
 'm': ['mongoose', 'malloo'],
 'persons': [('persons', 'man', 'woman')],
 'w': ['wombat']

现在是排序版本

 # but observe the sorted version where I have the data sorted first on same key I used for grouping
list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \
               'wombat', 'mongoose', 'malloo', 'camel']
sorted_list = sorted(list_things, key = lambda x: x[0])
print(sorted_list)
print()
c = groupby(sorted_list, key=lambda x: x[0])
dic = 
for k, v in c:
    dic[k] = list(v)
dic

结果

['cow', 'cat', 'camel', 'dog', 'donkey', 'goat', 'mulato', 'mongoose', 'malloo', ('persons', 'man', 'woman'), 'wombat']
'c': ['cow', 'cat', 'camel'],
 'd': ['dog', 'donkey'],
 'g': ['goat'],
 'm': ['mulato', 'mongoose', 'malloo'],
 'persons': [('persons', 'man', 'woman')],
 'w': ['wombat']

示例 3

things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "harley"), \
          ("vehicle", "speed boat"), ("vehicle", "school bus")]
dic = 
f = lambda x: x[0]
for key, group in groupby(sorted(things, key=f), f):
    dic[key] = list(group)
dic

结果

'animal': [('animal', 'bear'), ('animal', 'duck')],
 'plant': [('plant', 'cactus')],
 'vehicle': [('vehicle', 'harley'),
  ('vehicle', 'speed boat'),
  ('vehicle', 'school bus')]

现在是排序版本。我在这里将元组更改为列表。无论哪种方式,结果都相同。

things = [["animal", "bear"], ["animal", "duck"], ["vehicle", "harley"], ["plant", "cactus"], \
          ["vehicle", "speed boat"], ["vehicle", "school bus"]]
dic = 
f = lambda x: x[0]
for key, group in groupby(sorted(things, key=f), f):
    dic[key] = list(group)
dic

结果

'animal': [['animal', 'bear'], ['animal', 'duck']],
 'plant': [['plant', 'cactus']],
 'vehicle': [['vehicle', 'harley'],
  ['vehicle', 'speed boat'],
  ['vehicle', 'school bus']]

【讨论】:

"itertools.groupby(iterable, key=None or some func) 采用可迭代列表" 它采用可迭代列表还是仅采用可迭代列表?列表是可迭代的。 文档没有明确说明。但是从我发布的示例中,您可以看到我同时使用了列表和嵌套列表。因此它可以采用“可迭代”(示例 1)以及“可迭代列表”(示例 2)。你甚至可以传入一个字符串,你仍然可以做生意

sigaddset 是做啥用的?

】sigaddset是做啥用的?【英文标题】:Whatissigaddsetusedfor?sigaddset是做什么用的?【发布时间】:2014-12-0111:37:41【问题描述】:我有这段代码,我使用sigaddset和sigaction。但是,如果我评论segaddset结果是一样的structsigactionact;act.sa_handl... 查看详情

maven.multiModuleProjectDirectory 是做啥用的?

】maven.multiModuleProjectDirectory是做啥用的?【英文标题】:Whatismaven.multiModuleProjectDirectoryusedfor?maven.multiModuleProjectDirectory是做什么用的?【发布时间】:2015-06-2823:19:04【问题描述】:我在SO和Maven邮件列表上看到了很多关于设置env参... 查看详情

cursor.setNotificationUri() 是做啥用的?

】cursor.setNotificationUri()是做啥用的?【英文标题】:Whatiscursor.setNotificationUri()usedfor?cursor.setNotificationUri()是做什么用的?【发布时间】:2014-03-0415:02:29【问题描述】:我研究了如何使用ContentProviders和来自thistutorial的加载器我是怎... 查看详情

渠道是做啥用的?

】渠道是做啥用的?【英文标题】:Whatarechannelsusedfor?渠道是做什么用的?【发布时间】:2017-02-1102:35:37【问题描述】:在查看一些Go代码时,我发现了以下内容:ch:=make(chanint)我查阅了一个在线教程,了解GoChannels的工作原理:ht... 查看详情

MAKEWORD 是做啥用的?

】MAKEWORD是做啥用的?【英文标题】:WhatisMAKEWORDusedfor?MAKEWORD是做什么用的?【发布时间】:2014-06-1002:14:20【问题描述】:我在一段教学代码中遇到了这个宏MAKEWORD(2,2)。我在MSDN中读到它“通过连接指定的值来创建一个WORD值。”... 查看详情

Laravel 中的 `HtmlString` 是做啥用的?

】Laravel中的`HtmlString`是做啥用的?【英文标题】:Whatis`HtmlString`usedforinLaravel?Laravel中的`HtmlString`是做什么用的?【发布时间】:2017-07-0806:01:45【问题描述】:本课程:HtmlStringhtml=$html;/***获取HTML字符串。**@return字符串*/公共函数t... 查看详情

EasyMock.replay() 是做啥用的?

】EasyMock.replay()是做啥用的?【英文标题】:WhatisEasyMock.replay()usedfor?EasyMock.replay()是做什么用的?【发布时间】:2011-08-2415:14:28【问题描述】:我是单元测试和Junit的新手。我知道Junit的基础知识。我刚开始学习EasyMock框架。我无... 查看详情

SetPixelFormat() 中的 PIXELFORMATDESCRIPTOR 参数是做啥用的?

】SetPixelFormat()中的PIXELFORMATDESCRIPTOR参数是做啥用的?【英文标题】:WhatisthePIXELFORMATDESCRIPTORparameterinSetPixelFormat()usedfor?SetPixelFormat()中的PIXELFORMATDESCRIPTOR参数是做什么用的?【发布时间】:2010-03-2918:51:16【问题描述】:通常在设... 查看详情

Iterable 接口是做啥用的?

】Iterable接口是做啥用的?【英文标题】:WhatistheIterableinterfaceusedfor?Iterable接口是做什么用的?【发布时间】:2010-11-0617:52:36【问题描述】:我是初学者,无法理解Iterable界面的真实效果。【问题讨论】:【参考方案1】:除了Jere... 查看详情

predicateWithBlock: 中块的 bindings 参数是做啥用的?

】predicateWithBlock:中块的bindings参数是做啥用的?【英文标题】:WhatisthebindingsparameterfortheblockinpredicateWithBlock:usedfor?predicateWithBlock:中块的bindings参数是做什么用的?【发布时间】:2011-09-1914:10:01【问题描述】:+[NSPredicatepredicateWithB... 查看详情

app.config 是做啥用的?

】app.config是做啥用的?【英文标题】:Whatisapp.configfor?app.config是做什么用的?【发布时间】:2010-11-2817:44:52【问题描述】:Settings.settings生成Settings.Designer.cs,它可能会生成app.config,然后将其作为Foo.exe.config复制到输出目录。当... 查看详情

UITextInput 的 Tokenizer,它是做啥用的?

】UITextInput的Tokenizer,它是做啥用的?【英文标题】:TokenizerofUITextInput,whatisitusedfor?UITextInput的Tokenizer,它是做什么用的?【发布时间】:2013-05-0210:17:12【问题描述】:我正在实现一个自定义文本输入视图,它采用UITextInput协议,... 查看详情

namedtuple 的第一个参数是做啥用的?

】namedtuple的第一个参数是做啥用的?【英文标题】:What\'sthefirstargumentofnamedtupleusedfor?namedtuple的第一个参数是做什么用的?【发布时间】:2015-08-1202:46:34【问题描述】:我们像这样使用namedtuple:>>>fromcollectionsimportnamedtuple&... 查看详情

eq是做啥用的,它和压缩一样吗.如果不一样那压缩是做啥用的~

EQ是频率均衡器,它能够允许用户主动地对声音的各频段进行增益或衰减的处理。压缩是是对电信号的处理装置,它会将过大的电压减弱,过小的电压增强,体现在声音上就是能够让音箱中放出的声音稳定在一个设定的范围,尤... 查看详情

用户定义的操作“类型”是做啥用的?

】用户定义的操作“类型”是做啥用的?【英文标题】:Whatistheuserdefinedaction"type"for?用户定义的操作“类型”是做什么用的?【发布时间】:2016-08-0801:43:29【问题描述】:这里的“类型”列有什么作用?【问题讨论】:... 查看详情

测试和设置是做啥用的?

】测试和设置是做啥用的?【英文标题】:WhatisTest-and-Setusedfor?测试和设置是做什么用的?【发布时间】:2008-09-2313:22:00【问题描述】:在阅读了Test-and-SetWikipediaentry之后,我仍然想知道“Test-and-Set的用途是什么?”我知道您可... 查看详情

cacert.pem 到底是做啥用的?

】cacert.pem到底是做啥用的?【英文标题】:Whatexactlyiscacert.pemfor?cacert.pem到底是做什么用的?【发布时间】:2013-02-0522:14:39【问题描述】:在我的PayPalPro支付页面中,我使用cURL函数curl_setopt_array()和以下选项:cUInCURLOPT_CAINFO=&gt... 查看详情

pyproject.toml 文件是做啥用的?

】pyproject.toml文件是做啥用的?【英文标题】:Whatispyproject.tomlfilefor?pyproject.toml文件是做什么用的?【发布时间】:2020-11-0900:26:03【问题描述】:背景我正准备尝试从GitHub下载的Python包,发现它没有setup.py,所以我无法安装它pipin... 查看详情