python if and not,Python if if()不起作用

这篇博客探讨了在Python代码中any函数不按预期工作的情况。问题源于使用了IPython的%pylab magic,这导致了内置的any函数被numpy的版本覆盖。解决方案是避免使用%pylab --no-import-all,或者直接引用__builtin__.any来调用原始的内置函数。文章还提醒在脚本中需要根据Python版本导入内置模块。
摘要由CSDN通过智能技术生成

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?

解决方案

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?

Here's why:

In [3]: any('b' in w for w in ['a', 'c'])

Out[3]: at 0x7f6756d1a948>

In [4]: any

Out[4]:

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值