【问题标题】:Creating a list of lists with regular expressions in python在 python 中使用正则表达式创建列表列表
【发布时间】:2019-04-01 07:36:18
【问题描述】:

我以为我已经成功地在 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

感谢您的宝贵时间!

【问题讨论】:

  • 您的预期输出是什么?
  • ['z', 'x', 'c', '/v', '/b', '/n']
  • 它与您帖子中包含的输出有何不同?
  • 对不起,让我澄清一下。 print(no_tags[0]) 应该返回 ['z', 'x', 'c', '/v', '/b', '/n']。现在它返回每个列表中的第一项。
  • 您一定混淆了printreturn。了解差异并决定是要打印结果还是返回结果。目前,您打印列表和第一项,并且什么都不返回。你得到的正是你想要的,

标签: python python-3.x list nsregularexpression


【解决方案1】:

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

【讨论】:

  • 如果 OP 听从你的建议,只会打印最后的结果。
  • @DYZ 编辑帖子
  • 解决了!感谢您的帮助。
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 2013-11-24
  • 2014-10-14
  • 2012-09-02
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多