python仅在没有匹配项时添加到列表中

时间:2017-10-16 18:27:18

标签: python

我有一个以" redhat-release"

开头的rhel包列表

我想过滤出包含其中注释的包:

红帽释放-NOTES-5Server-5.x86_64

我正在遍历包列表

CV_PKG_RHEL_LST = []
for pkg_name in cv_packages_dic['results']:
    h_rl_server = pkg_name['nvrea']
    if re.match("redhat-release-notes", rh_rl_server) is  None:
        CV_PKG_RHEL_LST.append(rh_rl_server)

并尝试仅添加那些不包含字符串

的包

with:redhat-release-notes

但它不适合我,包括包含的包 "红帽释放香"

如何从列表中筛选出包含以下内容的包: "红帽释放香" ?

3 个答案:

答案 0 :(得分:1)

如果它是子字符串,您可以使用in前面的指令not

CV_PKG_RHEL_LST = []
for pkg_name in cv_packages_dic['results']:
    h_rl_server = pkg_name['nvrea']
    if "redhat-release-notes" not in rh_rl_server:
        CV_PKG_RHEL_LST.append(rh_rl_server)

答案 1 :(得分:0)

Python提供了两种基于正则表达式的不同原语操作:re.match()仅在字符串的开头检查匹配,而re.search()检查在字符串中匹配任何地方(这是Perl默认执行的操作)。 python doc

使用re.match(),您需要添加模式.*(模式开头的python add ^):

CV_PKG_RHEL_LST = []
for pkg_name in cv_packages_dic['results']:
    h_rl_server = pkg_name['nvrea']
    if re.match(".*redhat-release-notes", rh_rl_server) is  None:
        CV_PKG_RHEL_LST.append(rh_rl_server)

或更好地使用re.search()

CV_PKG_RHEL_LST = []
for pkg_name in cv_packages_dic['results']:
    h_rl_server = pkg_name['nvrea']
    if re.search("redhat-release-notes", rh_rl_server) is  None:
        CV_PKG_RHEL_LST.append(rh_rl_server)

答案 2 :(得分:0)

这样做的pythonic方法是使用列表理解,如下所示:

GET /workbook/worksheets/{id|name}/range(address='<address>')