日常踩坑记录:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

解决办法直接跳到末尾

目的:想要判断一个列表是否在另外的列表中
这里先说我正常能实现的结果:

eg:
z = [[2, 2, 2, 2], [1, 1, 1, 2]]
z1 = [-1.35, 2, 3, 4]
z2 = [2, 2, 2, 2]

# 判断z1 是否在 z 中:
if z1 not in z: # 如果 z1 不在 z 中,打印“zno”
    print("zno")
# 结果:zno

# 判断z2 是否在 z 中:
if z2 in z: # 如果 z2 不在 z 中,打印“zno”
    print("zno")
# 结果:zno

但是在我另外一个需求中,需要用到的数据是 numpy.ndarray 格式的:

z = np.array([[2, 2, 2, 2], [1, 1, 1, 2]],dtype=np.float32)
z1 = np.array([-1.35, 2, 3, 4],dtype=np.float32)

如果此时进行判断z1 是否在 z 中:
if z1 not in z: # 如果 z1 不在 z 中,打印“zno”
    print("zno")
    
# 结果:什么也不输出

从而想到将其转换为列表类型:

z = list(np.array([[2, 2, 2, 2], [1, 1, 1, 2]],dtype=np.float32))
z1 = list(np.array([-1.35, 2, 3, 4],dtype=np.float32))

此时进行判断z1 是否在 z 中:
if z1 not in z: # 如果 z1 不在 z 中,打印“zno”
    print("zno")
    
# 结果:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

解决办法:用 numpy 内置的类型转换函数 .tolist()

z = np.array([[2, 2, 2, 2], [1, 1, 1, 2]],dtype=np.float32)
z1 = np.array([-1.35, 2, 3, 4],dtype=np.float32)

if y1.tolist() not in y.tolist():# 如果 z1 不在 z 中,打印“zno”
    print("zno")
    
# 结果:zno

至于为什么的话,没有深究,所以我也不知道

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值