簡體   English   中英

在Python中,為什么這一行從文件運行(無例外),但在shell中運行時拋出異常?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM