用正则表达式在python中创建一个列表

2024-06-11 08:39:32 发布

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

我以为我已经在python中使用正则表达式成功地创建和过滤了一个列表列表。但是,当我试图索引列表时,我只索引每个列表中的第一项。仔细一看,我发现我的单子上没有逗号。我想知道如何将这些单独的列表转换为列表列表?在

我想这样做,这样我就可以引用不同的列表,并说明这些列表是否满足特定的标准。在

import re



 list_of_strings = ['''<z><x><c></v></b></n>''',
 '''<paa>mnb<ore>mnbczx</bar><e>poiuy</e></paa>''',
 '''<paa><ore></lan></ore></paa>''',
 '''<paa><ore></ore></paa></paa>''',
 '''<paa><ore></paa></ore>''']
def valid_html(list_of_strings):
    matches = [[s] for s in list_of_strings]
    lst = []
    for item in matches:
        tagsRegex = re.compile(r'(<.{0,3}>|</.{0,3}>)')
        lst = (tagsRegex.findall(str(item)))
        find = re.compile(r'(<)|(>)')
        no_tags = [find.sub('', t) for t in lst]
        print(no_tags)
        print(no_tags[0])
valid_html(test_strings)

我的输出是:

^{pr2}$

感谢您抽出时间!在


Tags: ofnoinre列表forhtmltags
1条回答
网友
1楼 · 发布于 2024-06-11 08:39:32

你在循环中插入并在循环中打印。你需要在for循环外打印需要返回相同的

def valid_html(list_of_strings):
    matches = [[s] for s in list_of_strings]
    lst = []
    l=[]
    for item in matches:
        tagsRegex = re.compile(r'(<.{0,3}>|</.{0,3}>)')
        lst = (tagsRegex.findall(str(item)))
        find = re.compile(r'(<)|(>)')
        no_tags = [find.sub('', t) for t in lst]
        l.append(no_tags)
    return l
valid_html(list_of_strings)[0]

相关问题 更多 >