python - 在 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
感谢您的时间!
解决方案
您正在循环内插入并在循环内打印。您需要在需要返回相同的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]
推荐阅读
- python - Python向用户输入文件路径添加反斜杠和引号,不会打开
- arrays - Swift 数组 reversed()[n] 是否有效?
- powerbi - Rankx Measure with countrows 返回 1
- python - 如何使用简单功能比较两个同音字
- rust - 添加特征以扩展内置类型
- javascript - window.onload 在索引数据库语句之前开始
- html - 使用 CSS 将 div 作为子标签移动到与父标签相同
- c# - Unity 水平重力与角色控制器
- arrays - 我无法访问从表对象填充的数组中的单个成员
- visual-studio - 安装 Microsoft Visual Studio 2013 时出错