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

Python中使用np.fromiter生成含指定第四列的多维数组问题

生成指定多维数组的问题

我在Jupyter Notebook中尝试生成一个多维数组,期望得到指定的输出结果。我尝试了多段代码,但始终无法生成数值范围为30-35的第四列,目前最接近的代码如下:

import numpy as np
from itertools import chain

def fun(i):
    return tuple(4*i + j for j in range(4))

a = np.fromiter(chain.from_iterable(fun(i) for i in range(6)), 'i', 6 * 4)
a.shape = 6, 4

print(repr(a))

我期望的结果是:

array([[ 1,  2,  3, 30],
       [ 4,  5,  6, 31],
       [ 7,  8,  9, 32],
       [10, 11, 12, 33],
       [13, 14, 15, 34],
       [20, 21, 22, 35]])

解决方案

原有代码的生成逻辑和目标数组规律不匹配,以下两种修改方式可以得到期望结果:

方法一:分步构建数组

先拆分生成前三个列的内容,再拼接第四列,同时处理第六行的特殊值:

import numpy as np

# 生成前5行的前3列:1-15按3个一组拆分
first_part = np.arange(1, 16).reshape(5, 3)
# 添加第六行的前3列
full_first_three = np.vstack([first_part, [20, 21, 22]])
# 生成第四列并拼接成最终数组
target_array = np.hstack([full_first_three, np.arange(30, 36).reshape(-1, 1)])

print(repr(target_array))

方法二:修改生成函数

调整fun函数逻辑,分别处理前五行和第六行的前三个元素,直接生成第四列的目标值:

import numpy as np
from itertools import chain

def fun(i):
    # 前五行的前三个元素按连续3数递增
    if i < 5:
        first_three = tuple(3*i + 1 + j for j in range(3))
    # 第六行使用特殊值
    else:
        first_three = (20, 21, 22)
    # 第四列从30开始依次递增
    fourth = 30 + i
    return first_three + (fourth,)

a = np.fromiter(chain.from_iterable(fun(i) for i in range(6)), 'i', 6 * 4)
a.shape = 6, 4

print(repr(a))

两种方法运行后都能输出你期望的数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:15:35