Python if if()不起作用

Ada*_*NYC 2 python if-statement numpy ipython

我想检查列表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!
Run Code Online (Sandbox Code Playgroud)

我该怎么解决这个问题?

Lev*_*sky 12

如果你使用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?
Run Code Online (Sandbox Code Playgroud)

原因如下:

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>
Run Code Online (Sandbox Code Playgroud)

anyall得到numpy函数的阴影,这些行为与内置函数不同.这就是我停止使用%pylab并开始使用的原因,%pylab --no-import-all因此它不会像这样破坏命名空间.

要在已经阴影的情况下到达内置函数,您可以尝试__builtin__.any.这个名称__builtin__似乎可以在Python 2和Python 3上的IPython中使用,它本身可能由IPython启用.在脚本中,您首先必须import __builtin__使用Python 2和import builtinsPython 3.

  • `*`进口是邪恶的. (7认同)
  • @ 2rs2ts:NumPy不会影响"任何".这是"导入*",它会影响"任何".命名空间的全部意义在于您不必担心使用其他人已经选择的名称.您可以看到标准库无需担心内置名称; 例如,`math.pow`和`codecs.open`都隐藏内置函数,如果`import*`ed. (3认同)