【问题标题】:Grouping string into substrings将字符串分组为子字符串
【发布时间】:2018-06-09 20:06:51
【问题描述】:

我需要解释一下这段代码是如何工作的。我不明白 for 循环中需要“str”和“grp”。他们在跟踪什么?

from itertools import groupby
print(["".join(grp) for str, grp in groupby('aaacaccccccbbbb')])

【问题讨论】:

标签: python python-3.x for-loop group-by itertools


【解决方案1】:

groupby 按一些key 对连续迭代器进行分组。如果未指定键,则默认分组谓词是连续元素应该相同。因此,总而言之,groupby 将相同的连续元素组合在一起。

用尽groupby,你会看到它返回元组:

list(groupby('aaacaccccccbbbb'))

[('a', <itertools._grouper at 0x12f132a58>),
 ('c', <itertools._grouper at 0x12f132d30>),
 ('a', <itertools._grouper at 0x12f132cf8>),
 ('c', <itertools._grouper at 0x12f1b9da0>),
 ('b', <itertools._grouper at 0x12f1a68d0>)]

每个元组是一对&lt;group_key, [group_values_iterator]&gt;,对应列表推导中的strgrpgrp 基本上是该组中的元素。列表理解耗尽了 grp 迭代器并将字符连接在一起。

【讨论】:

    【解决方案2】:

    不要使用内置函数作为变量名:str,int,set,dict,tuple,list,max,min,...

    如果有疑问,请将列表推导分解为其部分并将它们提供给打印语句 (How to debug small programs):

    from itertools import groupby
    grouping = groupby('aaacaccccccbbbb')
    
    for stri, grp in grouping: 
        print(stri)              # key of the grouping
        print(list(grp))         # group (use list to show it instead of the groupingiterable)
        print("")
    

    输出:

    a
    ['a', 'a', 'a']
    
    c
    ['c']
    
    a
    ['a']
    
    c
    ['c', 'c', 'c', 'c', 'c', 'c']
    
    b
    ['b', 'b', 'b', 'b']
    

    如果您对此仍有疑问,请阅读 API 或搜索 SO:How do I use Python's itertools.groupby()?

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 2015-12-28
      • 2015-06-06
      • 2011-11-25
      • 1970-01-01
      • 2015-01-13
      • 2012-02-22
      相关资源
      最近更新 更多