gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:35:48 25 4
gpt4 key购买 nike

我有元组列表。某些元组必须根据其项目值从列表中排除。下面是包含 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com