检查python列表中的所有项是否都包含子字符串

时间:2017-05-22 16:39:54

标签: python

我有一个python列表,我从api获取:

ERRATA_PKG_LIST = []
packages_key = "packages"
for pkgs, package_name in errata_rhel_ver_dic.iteritems():
    if pkgs == packages_key:
       ERRATA_PKG_LIST.append(package_name)
print(ERRATA_PKG_LIST)

输出:

[u'kernel-2.6.18-416.el5.i686',
 u'kernel-2.6.18-416.el5.x86_64',
 u'kernel-debug-2.6.18-416.el5.i686',
 u'kernel-debug-2.6.18-416.el5.x86_64',
 u'kernel-debug-devel-2.6.18-416.el5.i686',
 u'kernel-debug-devel-2.6.18-416.el5.x86_64',
 u'kernel-devel-2.6.18-416.el5.i686',
 u'kernel-devel-2.6.18-416.el5.x86_64',
 u'kernel-doc-2.6.18-416.el5.noarch',
 u'kernel-headers-2.6.18-416.el5.i386',
 u'kernel-headers-2.6.18-416.el5.x86_64',
 u'kernel-PAE-2.6.18-416.el5.i686',
 u'kernel-PAE-devel-2.6.18-416.el5.i686',
 u'kernel-xen-2.6.18-416.el5.i686',
 u'kernel-xen-2.6.18-416.el5.x86_64',
 u'kernel-xen-devel-2.6.18-416.el5.i686',
 u'kernel-xen-devel-2.6.18-416.el5.x86_64']

我想检查列表中的每个项目是否包含子字符串:el5 如果列表中的所有对象都包含el5,则分配变量 rhel =" rhel 5" ,我该如何实现?

4 个答案:

答案 0 :(得分:9)

要测试每个项目是否符合特定条件,请尝试使用内置函数all()generator expression。在生成器表达式中,子字符串包含的测试是in operator

要过滤列表,只选择符合某些条件的项目,请使用list comprehension

要打印列表,str.join()方法通常很有用。

Sub funcOffset()
Dim i As Long, j As Long
For j = 1 To 255
For i = 1 To Cells(Rows.Count, j).End(xlUp).Row
    If Cells(i, j) = "COUNTRY" Or InStr(Cells(i, j), "COUNTRY") > 0 Then
        Cells(i, j + 1) = "UK"
    End If
Next i
Next j
End Sub

答案 1 :(得分:3)

if all(['el5' in item for item in ERRATA_PKG_LIST]):
    rhel = "rhel 5"

答案 2 :(得分:1)

if all(map(lambda pkg: "el5" in pkg, ERRATA_PKG_LIST)):
        rhel = "rhel 5"

答案 3 :(得分:0)

您可以尝试使用in

def CheckList(list_items):
    for item in list_items:
        if 'el5' not in item:
            return False
    return True

这样你就可以遍历列表中的所有元素并检查子串'el5'是否不在该项中,如果该值为true,则函数返回False。否则,它将结束循环并返回True。