python-3.x - 在 Python 中连接数组 - 输出错误
问题描述
我正在编写一个程序来连接两个 numpy 数组,我希望程序为每个可能的结果(水平、垂直或不连接)打印一条消息。我有以下代码,但我不明白为什么即使满足第一个条件(np.hstack),它也会继续评估后续的if和else语句并错误地打印出同时存在水平串联(满足第一个条件)和连接是不可能的。
import numpy as np
def fun1(a,b):
if a.shape[0] == b.shape[0]:
print("The horizontal concatenation is:", np.hstack((a,b)))
if a.shape[1] == b.shape[1]:
print("The vertical concatenation is:", np.vstack((a,b)))
else:
print("These arrays cannot be concatenated.")
a = np.floor(10*np.random.random((3,2)))
b = np.floor(10*np.random.random((3,4)))
fun1(a,b)
输出:
The horizontal concatenation is: [[5. 0. 1. 1. 3. 7.]
[4. 1. 8. 3. 1. 9.]
[9. 1. 5. 7. 0. 0.]]
These arrays cannot be concatenated.
解决方案
而不是 else 部分,您需要具有此条件的第三个 if 语句:
if a.shape[0] == b.shape[0]:
print("The horizontal concatenation is:", np.hstack((a,b)))
if a.shape[1] == b.shape[1]:
print("The vertical concatenation is:", np.vstack((a,b)))
if a.shape[0] != b.shape[0] and a.shape[1] != b.shape[1]:
print("These arrays cannot be concatenated.")
推荐阅读
- r - How to "arrange" aggregate variable in dbplyr?
- java - 如何仅使用 cactoos 从文件中获取除以 # 开头的行之外的行
- openid-connect - 带有 oidc-client-js 的 Azure B2C 接收“错误:令牌中的颁发者无效”
- r - 在 R 中绘制一段时间内的销售额
- java - I don't know why the loop doesn't stop! Java
- c - 我需要帮助我的代码有问题并改进我的代码?
- xpath - 使用 Google 表格 + IMPORTXML 提取财务报表数据
- python - 从列表中的字符串中拆分每个字符
- vba - Comment.Add in Word VBA (2019) 在向评论中添加文本时不一致
- cefsharp - 有什么方法可以将 Service Worker 与 CEFSharp 一起使用?