Python中的if any()无效
我想检查一个列表 phrases
中的字符串元素是否包含一组特定的关键词 phd_words
。我想用 any
这个方法,但它没有效果。
In[19]:
import pandas as pd
import psycopg2 as pg
def test():
phd_words = set(['doctor', 'phd'])
phrases = ['master of science','mechanical engineering']
for word in phrases:
if any(keyword in word for keyword in phd_words):
return 'bingo!'
test()
Out[20]:
bingo!
我该怎么修复这个问题呢?
1 个回答
13
如果你使用了IPython的%pylab
这个魔法命令,就可能会出现这种情况:
In [1]: %pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib
In [2]: if any('b' in w for w in ['a', 'c']):
...: print('What?')
...:
What?
原因如下:
In [3]: any('b' in w for w in ['a', 'c'])
Out[3]: <generator object <genexpr> at 0x7f6756d1a948>
In [4]: any
Out[4]: <function numpy.core.fromnumeric.any>
any
和all
这两个函数会被numpy
库里的函数覆盖,而这些函数的行为和内置的函数不一样。这就是我为什么停止使用%pylab
,转而使用%pylab --no-import-all
的原因,这样就不会像之前那样搞乱命名空间。
如果你想在函数被覆盖的情况下调用内置函数,可以尝试使用__builtin__.any
。在IPython中,__builtin__
这个名字在Python 2和Python 3中似乎都是可用的,这可能是IPython自己提供的。在脚本中,如果你使用的是Python 2,你需要先import __builtin__
,而在Python 3中则需要import builtins
。