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

如何用两个列表创建numpy.recarray?附示例需求

当然有简便方法啦!咱们一步步来搞定你想要的numpy.recarray:

具体实现步骤

首先得把你的两个列表做个小处理——让list1里的每个字符串重复对应次数(这里每个字母要匹配4个数字,因为list2有12个元素,list1有3个,12÷3=4),然后把处理后的字符串列表和list2组合成结构化数组,最后转成recarray就行。

直接高效的代码示例

import numpy as np

list1 = ["a","b","c"]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

# 计算每个字符串需要重复的次数
repeat_count = len(list2) // len(list1)
# 把list1里的每个元素重复指定次数,生成和list2长度一致的数组
repeated_strs = np.repeat(list1, repeat_count)
# 用fromarrays直接创建recarray
rec_array = np.core.records.fromarrays(
    [repeated_strs, list2],
    dtype=[('string', '|U5'), ('int', '<i4')]
)

# 查看结果
print(rec_array)

运行这段代码后,输出的rec_array就和你期望的完全一样啦!

补充:另一种实现方式(先创建结构化数组再转换)

如果你更习惯先构建普通的结构化数组,再转成recarray,也可以这么写:

import numpy as np

list1 = ["a","b","c"]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

repeat_count = len(list2) // len(list1)
repeated_strs = np.repeat(list1, repeat_count)

# 先创建结构化数组
structured_arr = np.array(
    list(zip(repeated_strs, list2)),
    dtype=[('string', '|U5'), ('int', '<i4')]
)
# 转换为recarray
rec_array = structured_arr.view(np.recarray)

两种方法都能达到目的,第一种用np.core.records.fromarrays更直接,效率也更高哦。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:50:24