2016-12-14 29 views
-1
In [7]: a 
Out[7]: array(['107', '207', '307', '407'], dtype=object) 

In [8]: v 
Out[8]: array([207, 305, 407, 101]) 

In [9]: np.searchsorted(a, v) 
Out[9]: array([0, 0, 0, 0]) 

使用Python 3不過,我得到爲什麼犯規`searchsorted`工作一樣在Python 3和Python 2

In [20]: a 
Out[20]: array(['107', '207', '307', '407'], dtype=object) 

In [21]: v 
Out[21]: array([207, 305, 407, 101]) 

In [22]: np.searchsorted(a, v) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-22-52fb08e43089> in <module>() 
----> 1 np.searchsorted(a, v) 

/tmp/py3test/lib/python3.4/site-packages/numpy/core/fromnumeric.py in searchsorted(a, v, side, sorter) 
    1091  except AttributeError: 
    1092   return _wrapit(a, 'searchsorted', v, side, sorter) 
-> 1093  return searchsorted(v, side, sorter) 
    1094 
    1095 

TypeError: unorderable types: str() > int() 

我的問題是:是在Python3或錯誤此預期的行爲?無論如何:我怎樣才能讓我的Python 2代碼兼容Python版本?

+2

爲什麼你對象數組滿弦的搜索整數? – user2357112

+1

這不是關於實際搜索的內容。這裏有一個相關的問題:http://stackoverflow.com/q/3270680/2285236 – ayhan

+0

爲什麼downvotes? – wirrbel

回答

2

搜索用繩子,

In [278]: a=np.array(['107', '207', '307', '407'], dtype=object) 
In [279]: a 
Out[279]: array(['107', '207', '307', '407'], dtype=object) 
In [280]: np.searchsorted(a,'207') 
Out[280]: 1 
In [281]: np.searchsorted(a,207) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-281-a2d90678474c> in <module>() 
----> 1 np.searchsorted(a,207) 

/usr/local/lib/python3.5/dist-packages/numpy/core/fromnumeric.py in searchsorted(a, v, side, sorter) 
    1091  except AttributeError: 
    1092   return _wrapit(a, 'searchsorted', v, side, sorter) 
-> 1093  return searchsorted(v, side, sorter) 
    1094 
    1095 

TypeError: unorderable types: str() > int() 

或數字:

In [282]: np.searchsorted(a.astype(int),207) 
Out[282]: 1 

不要不理解他們是如何相互作用的混合字符串和數字。

如果Py2給出了0而不是錯誤,那只是因爲它對數字和字符串的比較不在意。

在PY3:

In [283]: '207'>207 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-283-834e0a472e1a> in <module>() 
----> 1 '207'>207 

TypeError: unorderable types: str() > int() 

在py2.7

>>> '207'>207 
True 
相關問題