返回一个计算的布尔pythonic或我应该使用传统的if/else?

Ada*_*ver 5 python

我想知道以下哪些示例在Python社区中更受欢迎:

1.

return any(host[0].endswith(bot_hosts) for bot_hosts in bot_hosts)
Run Code Online (Sandbox Code Playgroud)

2.

if any(host[0].endswith(bot_hosts) for bot_hosts in bot_hosts):
    return True
else:
    return False
Run Code Online (Sandbox Code Playgroud)

或者别的什么?

请指教.

roo*_*oot 4

在您的示例中:str.endswith将元组作为参数。总的来说,作为设计模式,使用第一个版本(检查推理@Ben的答案)。即any(host[0].endswith(bot_host) for bot_host in bot_hosts)等同于:

host[0].endswith(bot_hosts) #if bot_hosts is a tuple
                            #if bot_hosts in not a tuple add tuple(bot_hosts)
Run Code Online (Sandbox Code Playgroud)

例子:

In [1]: suffs = ('a','b','d')

In [2]: 'asd'.endswith(suffs)
Out[2]: True

In [3]: 'asap'.endswith(suffs)
Out[3]: False
Run Code Online (Sandbox Code Playgroud)