【问题标题】:PythonXY, spyder and python any() functionPythonXY、spyder 和 python any() 函数
【发布时间】: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 的 allany 导入作用域,破坏了内置函数。见我的answer here

标签: python string numpy any spyder


【解决方案1】:

用这种方式修改你的代码:

keyword_list=['WASHER', 'SCREW']
all_text  = "test_string"
print any # so we can see where it comes from
mkgen = lambda: (word in all_text for word in keyword_list)
print list(mkgen()) # to see what we have

if any(mkgen()):
    print "any: some of the strings found in str"
else:
    print "any: no strings found in str"

if (True in mkgen()):
    print "in: some of the strings found in str"
else:
    print "in: no strings found in str"

这个程序使发生的事情一目了然:

  • 它会打印出any 的性质,因此您可以查看它是“正常”还是被某些import * 覆盖的版本
  • 它还会打印出生成的布尔值

如果您设法找出问题所在,请使用any() 变体。它更像 Python。

【讨论】:

  • 嗨,这不会改变我的最终结果:打印输出是[False, False] any: some of the strings found in str in: no strings found in str
  • @tinix84 您缺少打印输出的第一行:print any 给出了什么?这是必不可少的,因为它向我们展示了它是来自 Python 本身还是来自第 3 方模块。
  • 我的任何打印输出是:
猜你喜欢
  • 2013-07-07
  • 2013-09-01
  • 2021-07-24
  • 2021-10-07
  • 2013-04-13
  • 2013-10-23
  • 1970-01-01
相关资源
最近更新 更多