Python 列表理解条件过滤器语法

标签 python list python-2.7

我有元组列表。某些元组必须根据其项目值从列表中排除。下面是包含 2 个元组的列表示例:

orig_list = [('mydomain', '20150726', 'e-buyeasy.com', 'www.ujizlhekw.e', '1', 
'1', '1', '1', '100.0', '0.0'), 
('myotherdomain', '20150726', 'floating-share-buttons.com', '', '26',
'26', '26', '26', '100.0', '0.0')]

我创建了一个函数,该函数使用两个元组项与其他“查找”列表的正则表达式匹配。该函数根据与查找列表的匹配返回 True 或 False。

def tupMatch(tup):
    sourceReg="semalt.*","anticrawler.*","best-seo-offer.*","best-seo-solution.*","buttons-for-website.*","buttons-for-your-website.*","7makemoneyonline.*","-musicas*-gratis.*","kambasoft.*","savetubevideo.*","ranksonic.*","medispainstitute.*","offers.bycontext.*","100dollars-seo.*","sitevaluation.*","dailyrank.*","videos-for-your-business.*","videos-for-your-business.*","success-seo.*","4webmasters.*","get-free-traffic-now.*","free-social-buttons.*","trafficmonetizer.*","traffic2money.*","floating-share-buttons.*"

    hostnameReg="mydomain.*","myotherdomain.*"

    sourceReg2 = "(" + ")|(".join(sourceReg) + ")"
    hostnameReg2 = "(" + ")|(".join(hostnameReg) + ")"

    sourceMatch = re.match(sourceReg2, tup[2].lower())
    hostMatch = re.match(hostnameReg2, tup[3].lower())

    if (not sourceMatch) and (hostMatch):
        True
    else:
        False
    return

我有一个列表理解,可以根据函数结果过滤原始列表。

filtered_list = [tup for tup in orig_list if tupMatch(tup)]

然而,这实际上并没有过滤列表。我期望 'tupMatch(tup)' 将返回 True 或 False,并且列表理解将只有 True 的元组。

我在这里缺少什么?

最佳答案

以下行不会返回(没有return关键字);该函数隐式返回None;这被认为是错误值。

if (not sourceMatch) and (hostMatch):
    True
else:
    False

更改行如下:

if (not sourceMatch) and (hostMatch):
    return True
else:
    return False

或更短:

return (not sourceMatch) and (hostMatch)   # OR  return bool(...)

关于Python 列表理解条件过滤器语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31738633/

相关文章:

python - Python中C类型Switch语句实现的困惑

python - 将 for 循环添加到列表中

python - 属性错误 : 'module' object has no attribute 'startfile'

python-2.7 - 无效参数错误 : You must feed a value for placeholder tensor 'input_1/X' with dtype float

python - 使用 urllib.request 和 json 模块在 Python 中加载 JSON 对象

python - 从迭代器创建容器

python - PyQt5 QTextBrowser - setText - 对齐问题?

python - 在 Python 中合并列表

java - 如何将数组的值而不是该数组的位置添加到 ArrayList 中?

Python Selenium 返回文本,unicode 对象不可调用