如何使用相似的numpy nd数组创建数据结构

2024-04-20 06:10:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个功能:

def check_smaller_zeros(v):
   return v < 0

使用numpy创建阵列时,我可以编写下一个逐元素测量代码:

v_1 = numpy.array([1, 2, -4, -1])
result = check_smaller_zeros(v_1)
# result: [False, False, True, True]

但当我尝试用tuple、set、frozenset和list/array重复它时,会出现下一个错误:

TypeError: '<' not supported between instances of 'tuple' and 'int'

到底是什么允许numpy阵列具有这种行为的能力?这看起来很方便,但有点不明显


Tags: 代码功能numpyfalsetrue元素returndef
2条回答

数组与元组、列表等非常不同。 如果你想推广你的函数,你必须考虑每种情况

In [111]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    elif type(v) in (list, tuple):
     ...:        return [x<0 for x in v]
     ...:

In [112]: check_smaller_zeros((-1,1,2,3,4,5))
Out[112]: [True, False, False, False, False, False]

在某些情况下,您可以简单地将对象转换为np.array。但这取决于对象的形式,您必须提前定义用例

In [114]: def check_smaller_zeros(v):
     ...:    if type(v) is np.array:
     ...:        return v < 0
     ...:    else:
     ...:        return np.array(v) < 0
     ...:
     ...:

In [115]: check_smaller_zeros((-1,1,2,3,4,5))
Out[115]: array([True, False, False, False, False, False])

Python允许您使用特殊的“dunder”(双下划线)方法重写运算符。例如,让我们创建一个从tuple继承的自定义数据结构。要使<执行逐项比较,只需覆盖__lt__方法

In [1]: class MyList(tuple):
      :     def __lt__(self, other):
      :         return tuple(v < other for v in self)
      :

In [1]:

In [2]: l = MyList([1,2,3,4,5])

In [3]: l < 3
Out[3]: (True, True, False, False, False)

所有这些方法的列表都可以在Data Model下的Python文档中找到

相关问题 更多 >