You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Numpy生成的二进制数组每行添加固定-1序列?

解决方法

错误原因

你遇到的TypeError是因为np.row_stack()(和np.vstack()等价)要求传入一个包含多个数组的可迭代对象(比如列表),而你直接传递了两个独立参数,不符合函数调用规范。此外,原代码循环中反复使用np.append和row_stack会频繁复制数组,不仅逻辑混乱,效率也极低。

最优解决方案(向量化操作)

直接先生成完整的256×8二进制数组,再一次性拼接全为-1的256×8数组,这是Numpy推荐的高效做法:

# 生成原始256行8列的二进制数组
binary_strings = [utils.dec_to_bin(i, 8) for i in range(256)]
comprehensive_merged_function = np.array([list(s) for s in binary_strings], dtype=int)

# 生成每行对应要追加的8个-1组成的数组
appended_part = np.full_like(comprehensive_merged_function, -1)

# 水平拼接两个数组,得到256×16的目标数组
result = np.hstack([comprehensive_merged_function, appended_part])

如果要保留原循环生成逻辑,可优化为:

comprehensive_merged_function = np.zeros((256, 8), dtype=int)
for i in range(256):
    comprehensive_merged_function[i] = np.array(list(utils.dec_to_bin(i, 8)), dtype=int)

appended_part = np.full((256, 8), -1, dtype=int)
result = np.hstack([comprehensive_merged_function, appended_part])

修正原有循环代码(不推荐,仅作参考)

如果坚持逐行循环拼接,需修正vstack调用方式并调整逻辑:

# 初始化16列的空数组,提前指定维度避免反复扩容
comprehensive_merged_function = np.zeros((0, 16), dtype=int)
appending_indexes = np.array([-1]*8, dtype=int)

for i in range(256):
    # 获取当前8位二进制行
    bin_row = np.array(list(utils.dec_to_bin(i, 8)), dtype=int)
    # 拼接当前二进制行和-1的部分
    full_row = np.hstack([bin_row, appending_indexes])
    # 将完整行追加到总数组(注意vstack接收的是数组列表)
    comprehensive_merged_function = np.vstack([comprehensive_merged_function, full_row])

内容的提问来源于stack exchange,提问作者Petar Andreev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:15:55