在列表推导中使用Python any()函数
我刚开始学Python(才两周!),现在遇到了一些困难:
我有一堆网址,想要逐个检查,找出特定的网址。为此,我想测试一下某个元组里的元素是否出现在网址中。
我知道需要用到any()这个函数,但就是搞不清楚语法怎么写:
allurls = [<big list of URLs>]
words = ('bob', 'fred', 'tom')
urlsIwant = [x for x in allurls if any(w for w in words) in x]
这段代码给我的结果是
TypeError: 'in <string>' requires string as left operand, not bool
我觉得这可能不太相关,但我实际的代码是
urlsIwant = sorted(set([x for x in allurls if dict['value'] in x and any(w for w in words) in x]))
1 个回答
22
在 any()
里面加上 in x
:
urlsIwant = [x for x in allurls if any(w in x for w in words)]