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

如何使用NumPy基于两个数组快速生成新数组?遇实现问题求助

问题分析与解决方案

首先,你的原始列表推导式速度慢的原因是 second.index(digit) 每次查找都要遍历整个列表,时间复杂度为 O(n²),对于10万级数据来说效率极低。

现有NumPy代码错误原因

你使用 np.fromfunction() 的代码报错,核心问题是:

  • np.fromfunction() 会将数组形式的索引传递给lambda函数,而非单个标量索引。因此 second[x] 会返回整个 second 数组,导致 first == second[x] 生成一个二维布尔数组,后续的 np.where 和索引操作完全不符合预期逻辑。

高效NumPy实现方案

我们可以通过预构建值到索引的映射来实现O(n)时间复杂度的操作,具体步骤如下:

假设输入值为1~n的排列(符合示例场景)

这种情况下可以直接用数组作为 lookup 表,速度最快:

import numpy as np

n = int(input())
first = np.fromstring(input(), sep=' ', dtype=int)
second = np.fromstring(input(), sep=' ', dtype=int)

# 构建lookup表:lookup[数值] = 该数值在second中的索引
lookup = np.zeros(n + 1, dtype=int)
lookup[second] = np.arange(n)

# 生成结果:对first中每个元素,找到其在second中的索引,再取first对应位置的值
result = first[lookup[first]]

# 输出结果
print(' '.join(map(str, result)))

通用场景(输入值为任意唯一整数)

如果输入值不是1~n的排列,可通过排序+二分查找实现:

import numpy as np

n = int(input())
first = np.fromstring(input(), sep=' ', dtype=int)
second = np.fromstring(input(), sep=' ', dtype=int)

# 对second排序并记录原始索引
sorted_indices = np.argsort(second)
sorted_values = second[sorted_indices]

# 查找first中每个元素在排序后second中的位置,映射回原始索引
pos_in_sorted = np.searchsorted(sorted_values, first)
original_indices = sorted_indices[pos_in_sorted]

# 生成结果
result = first[original_indices]

# 输出结果
print(' '.join(map(str, result)))

验证示例

以你的输入为例:

  • first = [5,2,3,1,4],second = [1,3,2,4,5]
  • lookup表中:lookup[1]=0,lookup[3]=1,lookup[2]=2,lookup[4]=3,lookup[5]=4
  • lookup[first] = [4,2,1,0,3]
  • first[lookup[first]] = [4,3,2,5,1],与输出示例完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:27:30