【问题标题】:How to let groupby() group doubles with a condition?如何让 groupby() 组加倍有条件?
【发布时间】:2017-11-29 09:28:46
【问题描述】:

例子:

import regex
import itertools

m = "90.80.19 90.43.19 908019 92.11.15 90.80.19 930000"
reg = regex.compile("\d\d\.?\d\d\.?\d\d")
[list(g) for k, g in itertools.groupby(sorted(reg.findall(m)))]

Output: [['90.43.19'], ['90.80.19', '90.80.19'], ['908019'], ['92.11.15'], ['930000']]

groupby() 组合双精度:只有双精度 90.80.19 已分组。

我想要做的是按上面的正则表达式分组:\.? 在上面的正则表达式中是可选的。

Expected output: [['90.43.19'], ['90.80.19', '90.80.19', '908019'], ['92.11.15'], ['930000']]

是否可以让 groupby() 有条件的分组?

【问题讨论】:

    标签: python regex python-3.x pattern-matching itertools


    【解决方案1】:

    itertools.groupby(iterable, key=None) 使用自定义key 函数,如下所示(初始输入字符串已扩展):

    import re, itertools
    
    s = "90.80.19 90.43.19 908019 92.11.15 90.80.19 930000 921115"
    matches = re.findall(r'\d\d\.?\d\d\.?\d\d', s)
    result = [ list(g) for k,g in itertools.groupby(sorted(matches),
                                                    key=lambda x: x.replace('.', '') or x) ]
    
    print(result)
    

    输出:

    [['90.43.19'], ['90.80.19', '90.80.19', '908019'], ['92.11.15', '921115'], ['930000']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 2020-08-06
      • 2017-01-06
      相关资源
      最近更新 更多