包含多个元素的数组的真值

2024-10-03 06:32:41 发布

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

我在另一个文件中输入了日期数组,并在下面调用了此函数,但它返回了如下错误:

Traceback (most recent call last):
  File "/Users/jiangyunke/Desktop/My Python/Interest Rate Curve/venv/swap.py", line 21, in <module>
    "30/360": Z.X_30360()}
  File "/Users/jiangyunke/Desktop/My Python/Interest Rate Curve/venv/DayCountConvention.py", line 44, in X_30360
    + 30 * (d2_month - d1_month - 1)) / 360
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我如何处理这个问题? 代码如下:

def X_30360(self):
    d1_month = list(self.d1.month)
    d2_month = list(self.d2.month)
    d1_year = list(self.d1.year)
    d2_year = list(self.d2.year)
    if d2_month == d1_month:
        d_30360 = (360 * (d2_year - d1_year) + self.d2.day - self.d1.day) / 360
    else:
        d_30360 = (max(0, 30 - self.d1.day) + min(30, self.d2.day) + 360 * (d2_year - d1_year)
        + 30 * (d2_month - d1_month - 1)) / 360
    return d_30360

Tags: selfratemyyearuserslistfiled2
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:41

您有一个列表a = [False, True, True]。 真值是假还是真?这确实是模棱两可的

方法1-所有元素都必须为真

>>> a = [False, True]
>>> all(a)
False
>>> a = [True, True, True, True]
>>> all(a)
True
>>> a = [False, False, False]
>>> all(a)
False

方法2-至少一个值必须为真

>>> a = [False, True]
>>> any(a)
True
>>> a = [True, True, True, True]
>>> any(a)
True
>>> a = [False, False, False]
>>> any(a)
False

方法3-列表中只有一项

>>> a = [False]
>>> bool(a)
False
>>> a = [True]
>>> bool(a)
True

根据需要,如果希望至少有一个为真,请使用any(a),如果希望所有为真,请使用all(a)

相关问题 更多 >