为什么`searchsorted`在Python 3和Python 2中的工作方式不同

时间:2016-12-14 18:57:57

标签: python python-3.x numpy

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,我得到了

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版本?

1 个答案:

答案 0 :(得分: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