首页 > 解决方案 > 在 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)

我的输出是:

valid_html(test_strings)
['z', 'x', 'c', '/v', '/b', '/n']
z
['paa', 'ore', '/ore', 'e', '/e', '/paa']
paa
['paa', 'ore', '/lan', '/ore', '/paa']
paa
['paa', 'ore', '/ore', '/paa', '/paa']
paa
['paa', 'ore', '/paa', '/ore']
paa

感谢您的时间!

标签: pythonpython-3.xlistnsregularexpression

解决方案


您正在循环内插入并在循环内打印。您需要在需要返回相同的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]

推荐阅读