python 根据python中指定的正则表达式对字符串列表进行分组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 根据python中指定的正则表达式对字符串列表进行分组相关的知识,希望对你有一定的参考价值。

from re import search, findall

def group_strings(string_iterable, pattern_to_group_with):
    """ groups strings based on a given regex and returns the groups in a dict
        by: Cody Kochmann """
    groups={}
    for i in string_iterable:
        if search(pattern_to_group_with, i):
            group = findall(pattern_to_group_with, i)[0]
            if group in groups:
                groups[group].append(i)
            else:
                groups[group]=[i]
    return groups
    

以上是关于python 根据python中指定的正则表达式对字符串列表进行分组的主要内容,如果未能解决你的问题,请参考以下文章