[英]In Python, why does this line run from the file (without exception), but throw an exception when run in the shell?
我正在浏览Peter Norvig的Sudoku求解器代码( http://norvig.com/sudopy.shtml ),并且遇到了这一行:
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
如果我将代码复制到并包含此行(即直到第28行),并从文件中运行它,它运行正常,字典'peers'具有例外值。 但是,如果在我运行此文件后,我尝试从shell运行此行,我收到一个错误:
peers = dict((s, set(sum(units[s],[]))-set([s]))
for s in squares)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-33-2652de1ecd8a> in <module>()
1 peers = dict((s, set(sum(units[s],[]))-set([s]))
----> 2 for s in squares)
<ipython-input-33-2652de1ecd8a> in <genexpr>((s,))
1 peers = dict((s, set(sum(units[s],[]))-set([s]))
----> 2 for s in squares)
C:\PyCanopy\User\lib\site-packages\numpy\core\fromnumeric.pyc in sum(a, axis, dtype, out, keepdims)
1717 except AttributeError:
1718 return _methods._sum(a, axis=axis, dtype=dtype,
-> 1719 out=out, keepdims=keepdims)
1720 # NOTE: Dropping the keepdims parameters here...
1721 return sum(axis=axis, dtype=dtype, out=out)
C:\PyCanopy\User\lib\site-packages\numpy\core\_methods.pyc in _sum(a, axis, dtype, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
---> 32 return umr_sum(a, axis, dtype, out, keepdims)
33
34 def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: cannot perform reduce with flexible type
我无法弄清楚为什么会这样。 我发现这行代码开头很奇怪,因为它有一个dict
键值和空[]
的sum
。 任何指导? 谢谢。
代码在python
解释器和ipython
都适用于我。 看起来在运行代码之前你做了这个:
from numpy import sum
所以现在sum
不是python的标准sum
,但它是从numpy
导入的不同函数。 这就是代码引发错误的原因。
解决方案:从ipython
shell退出,再次运行并将代码粘贴到其中。
编辑 :关于空列表的总和,这只是使单位平坦的技巧。 例如,单位['I1']如下所示:
[['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1'],
['I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9'],
['G1', 'G2', 'G3', 'H1', 'H2', 'H3', 'I1', 'I2', 'I3']]
sum(units['I1'], [])
如下所示:
['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9', 'G1', 'G2', 'G3', 'H1', 'H2', 'H3', 'I1', 'I2', 'I3']
引擎盖下的总和是这样的:
list = []
for elem in units['I1']:
list = list + elem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.