gpt4 book ai didi

python - 如何让 groupby() 组在条件下加倍?

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:07 25 4
gpt4 key购买 nike

示例:

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() 对 double 进行分组:仅对 double 90.80.19 进行了分组。

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

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

是否可以让groupby()根据条件进行分组?

最佳答案

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']]

关于python - 如何让 groupby() 组在条件下加倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com