【问题标题】:In Python, why does this line run from the file (without exception), but throw an exception when run in the shell?在 Python 中,为什么这行从文件中运行(无异常),但在 shell 中运行时抛出异常?
【发布时间】:2016-01-20 11:06:51
【问题描述】:

我在浏览 Peter Norvig 的数独求解器代码 (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 

我无法弄清楚这是为什么。我发现这行代码一开始就很奇怪,因为它有一个sum,而不是dict 键加上一个空的[]。有什么指导吗?谢谢。

【问题讨论】:

  • 我无法回答您的主要问题,但是 Python 内置 sum 函数的第二个参数是起始值,默认情况下为零。通过提供[] 作为起始参数,它可以让您将列表列表展平为单个列表。例如,sum([[1],[2],[3]],[]) 的计算结果为 [1, 2, 3]

标签: python shell dictionary


【解决方案1】:

代码在python 解释器和ipython 中都适用于我。 看起来你在运行代码之前是这样做的:

from numpy import sum

所以现在sum 不是python 的标准sum,而是从numpy 导入的不同函数。 这就是代码引发错误的原因。

解决方法:退出ipython shell,再次运行,粘贴代码。

编辑:关于空列表的总和,使单位[s]变平只是一个技巧。 例如,单位['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

【讨论】:

  • 嗯。怎么样...我可以看到可能是这种情况,尽管我现在正在努力测试它。我似乎无法弄清楚为什么 Canopy 的解释器会自动加载 numpy,也不知道如何将其关闭。谢谢!
  • @nevakanezzar 欢迎您。我还更新了答案,解释了 sum(units[s], []) 的作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多