Python if if()不起作用 [英] Python if any() does not work
问题描述
我想检查列表词组
中的任何字符串元素是否包含集合 phd_words
中的某些关键字。我想使用任何
但它不起作用。
I want to check if any string elements in a list phrases
contains certain keywords in a set phd_words
. I want to use any
but it doesn't work.
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!
我该如何解决这个问题?
How should I fix this?
推荐答案
如果您使用IPython的%pylab
magic可能会发生这种情况:
That may happen if you use IPython's %pylab
magic:
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>
任何
和所有
被 numpy
函数遮蔽,并且这些函数与内置函数不同。这就是我停止使用%pylab
并开始使用%pylab --no-import-all
的原因,以便它并没有像这样破坏名称空间。
any
and all
get shadowed with numpy
functions, and those behave differently than the builtins. This is the reason I stopped using %pylab
and started using %pylab --no-import-all
so that it doesn't clobber the namespace like that.
要在内置函数已经被遮蔽时到达内置函数,你可以尝试 __ builtin __。any
。名称 __ builtin __
似乎在IPython中可用于Python 2和Python 3,它本身可能由IPython启用。在脚本中,您首先必须 import __builtin __
on Python 2和 import builtins
on Python 3。
To reach the builtin function when it is already shadowed, you can try __builtin__.any
. The name __builtin__
seems to be available in IPython on both Python 2 and Python 3, which is probably on itself enabled by IPython. In a script, you would first have to import __builtin__
on Python 2 and import builtins
on Python 3.
这篇关于Python if if()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!