首页 > 解决方案 > 关于列表中正则表达式使用的一个简单问题

问题描述

我在下面的列表中有一个列表为“list_all”,我正在寻找下面“c”中所述的单词。第二个列表中没有“c”。下面的代码给出的结果为 ['c', 'c'] 但我希望 ['c', '', 'c'] 具有相同的长度 'list_all'。请你帮我解决一下,我怎样才能把空元素放到结果中。

import re

    list_all = [['a','b','c','d'],['a','b','d'],['a','b','c','d','e']]
    
    listofresult =[]
    for h in [*range(len(list_all))]:
        for item in list_all[h]:
            patern = r"(c)"
            if re.search(patern, item):
                listofresult.append(item)
            else:
                None
    
    print(listofresult)

标签: pythonregexlist

解决方案


尝试这个

import re

list_all = [['a','b','c','d'],['a','b','d'],['a','b','c','d','e']]

temp = True
listofresult =[]
for h in range(len(list_all)):
    for item in list_all[h]:
        patern = r"(c)"
        if re.search(patern, item):
            listofresult.append(item)
            temp = False
    if temp:
        listofresult.append("")
    temp = True

print(listofresult)

推荐阅读