首页 > 解决方案 > 在 Python 中连接数组 - 输出错误

问题描述

我正在编写一个程序来连接两个 numpy 数组,我希望程序为每个可能的结果(水平、垂直或不连接)打印一条消息。我有以下代码,但我不明白为什么即使满足第一个条件(np.hstack),它也会继续评估后续的ifelse语句并错误地打印出同时存在水平串联(满足第一个条件)和连接是不可能的。

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.

标签: python-3.xnumpy

解决方案


而不是 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.")

推荐阅读