在循环中匹配和分组相似字符串集

2024-10-01 05:01:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个列表中匹配和分组相似的字符串,但我不确定如何处理这个问题。在

我有以下清单:

tablenames =[
            'SCS_q104',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid',
            'SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid',
            'SCS_q105',
            'SCS_q106',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid',
            'SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid',
            'SCS_q108',
            'SCS_q109',
            ]

预期结果:

^{pr2}$

从上面的预期结果你可以看到我是如何将字符串分组的。 如果方括号前后的所有内容都与前面的字符串相同,则它们属于单个组。在

本例中有两个组。在

预期的结果只需对匹配的字符串集进行分组,它是否存储为列表列表或某种dict并不重要。在

我目前的尝试:

groupofgrids = []
for item in tablenames:
    if "." in item:
        suffix = item.split(".")[-1]
        if suffix in item:
            groupofgrids.append(item)

print groupofgrids

这个方法并没有真正地按我想要的那样对一组相似的字符串进行分组,只是因为我不知道如何进行分组。在

有什么建议吗?在


Tags: 字符串in列表ifitemsuffixgridscs
2条回答

这对你有用吗:

group = dict()

for elm in tablenames:
    try:
        f,s = elm.split('.')
    except:
        pass
    else:
        group.setdefault(s,[])
        group[s].append(elm)

import pprint
pprint.pprint(group.values())

输出:

^{pr2}$

由于相似性是基于除方括号[...]之间的内容之外的字符串,所以提取这些子字符串,使用分隔符(这里我使用了"-")将它们连接起来,并将其用作字典的键
试试这个-

import re
regex = re.compile(r'(.*?)\[.*?\]\.(.*)')
groupofgrids = {}
for item in tablenames:
    matches = regex.findall(item)
    if (len(matches) > 0 and len(matches[0]) == 2):    
        key = "-".join(matches[0])
        if key in groupofgrids:
            groupofgrids[key].append(item)
        else:
            groupofgrids[key] = [item]
import json
print json.dumps(groupofgrids,sort_keys=True, indent=4)
#OUTPUT
'''
{
    "SCS_q102-SCS_q102_grid": [
        "SCS_q102[{SCS_q102$_$_$SCS_q102_1}].SCS_q102_grid", 
        "SCS_q102[{SCS_q102$_$_$SCS_q102_2}].SCS_q102_grid", 
        "SCS_q102[{SCS_q102$_$_$SCS_q102_3}].SCS_q102_grid", 
        "SCS_q102[{SCS_q102$_$_$SCS_q102_4}].SCS_q102_grid"
    ], 
    "SCS_q107-SCS_q107_grid": [
        "SCS_q107[{SCS_q107$_$_$SCS_q107_1}].SCS_q107_grid", 
        "SCS_q107[{SCS_q107$_$_$SCS_q107_2}].SCS_q107_grid", 
        "SCS_q107[{SCS_q107$_$_$SCS_q107_3}].SCS_q107_grid"
    ]
}
'''

如果需要嵌套列表,请执行以下操作-

^{pr2}$

相关问题 更多 >