【发布时间】:2014-02-05 09:14:24
【问题描述】:
我正在尝试使用 python 的函数 any() 搜索文本中的单词,我期望以下两个具有相同的行为,但事实并非如此:
keyword_list=['WASHER', 'SCREW']
all_text = "test_string"
if any(word in all_text for word in keyword_list):
print "some of the strings found in str"
else:
print "no strings found in str"
if (True in (word in all_text for word in keyword_list)):
print "some of the strings found in str"
else:
print "no strings found in str"
使用 python 2.7.5 在 Spyder 2.2.0 中运行(我下载了 pythonXY 包)结果与使用普通 cmd 控制台启动 python 不同。
其实Spyder里面的结果:
>>> runfile(r'C:\untitled0.py', wdir=r'C:\PythonTestbench')
some of the strings found in str
no strings found in str
其实结果里面的命令提示符:
>>> runfile(r'C:\untitled0.py', wdir=r'C:\PythonTestbench')
no strings found in str
no strings found in str
Spyder 环境有另一个版本的any() 函数,解释为here。
如何强制不使用 NumPy 中包含的函数?
【问题讨论】:
-
两个版本都打印
no strings found in str。怎么了? -
两者都产生 False——你的问题是什么?
-
对我有用,如果我将 'SCREW' 更改为 'string' 以便它们返回 True
-
嘿,我可以重现这种行为。在 IPython Notebook 中为 python 版本 2.7.3 找到了它,奇怪的是它在 IPython shell 中工作。在另一台计算机上,我使用的是 Python 2.7.5 版,并且无论哪种方式都可以正常工作。 @tinix84 你是如何运行你的代码的?
-
是的,这是因为 PythonXY 将 numpy 的
all和any导入作用域,破坏了内置函数。见我的answer here。
标签: python string numpy any spyder