如何将值保存到python中的列表

我正在尝试将值保存到列表中,但是当我这样做时,它为我提供了None值。不知道我到底在做什么错

for sentence in mylist:
    global typ,DN,pn
    matches = re.finditer(regex_f,sentence,re.MULTILINE | re.IGNORECASE)
    for matchNum,match in enumerate(matches,start=1):
        subst = sentence[match.end():]
        pn_matches = re.findall(regexp,subst,re.MULTILINE | re.IGNORECASE)

        if len(pn_matches) > 0:
            pn = pn_matches
            pn_p = ("{pn}".format(flansch=match.group(),pn=pn))
            print(pn)
            list_test = []
            dat_test = list_test.append(pn)
            print(dat_test)

        else:
            pn_p = '?'
            print("no PN found".format(flansch=match.group()))

['PN10']
None
['PN16']
None
['PN 40']
None

如果我直接从pn打印其工作值,但是当我将其附加到列表时,它会显示None。

leekikong1986 回答:如何将值保存到python中的列表

其他人已经说过list.append()没有返回值。这就是为什么dat_test始终设置为None的原因。

您应使用像list_test.append(pn)这样的append而不将其添加到新变量中。然后,如果您用print(list_test)代替print(dat_test),就可以了。

for sentence in mylist:
    global typ,DN,pn
    matches = re.finditer(regex_f,sentence,re.MULTILINE | re.IGNORECASE)
    for matchNum,match in enumerate(matches,start=1):
        subst = sentence[match.end():]
        pn_matches = re.findall(regexp,subst,re.MULTILINE | re.IGNORECASE)

        if len(pn_matches) > 0:
            pn = pn_matches
            pn_p = ("{pn}".format(flansch=match.group(),pn=pn))
            print(pn)
            list_test = []
            list_test.append(pn)
            print(list_test)

        else:
            pn_p = '?'
            print("no PN found".format(flansch=match.group()))

根据您的实际用例,我建议考虑将list_test放置在您的代码中,因为对于len(pn_matches) > 0的每个句子,它总是被重置为一个空列表。您将只获得列表中最后一个结果蜂!

编辑:

list_test = []
for sentence in mylist:
    global typ,pn=pn))
            print(pn)

            list_test.append(pn)
            print(list_test)

        else:
            pn_p = '?'
            print("no PN found".format(flansch=match.group()))
本文链接:https://www.f2er.com/3150960.html

大家都在问