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

如何在Python中从数组中选取指定元素?

数组元素提取解决方案

完全可行,目标数组里的所有元素都包含在原数组中,直接提取即可。下面是两种实用的Python实现方式:

方式一:按元素值直接筛选

用列表推导式过滤出原数组中属于目标列表的元素,适合不确定元素位置的场景:

original_array = list(range(1, 90))
target_elements = [17,19,20,21,40,45,54,65,74,77,82]

result = [num for num in original_array if num in target_elements]
print(result)
# 输出: [17, 19, 20, 21, 40, 45, 54, 65, 74, 77, 82]

方式二:按元素索引提取

因为原数组是连续整数,元素值和索引存在固定对应关系(索引=元素值-1),通过索引提取效率更高:

original_array = list(range(1, 90))
target_elements = [17,19,20,21,40,45,54,65,74,77,82]

# 计算目标元素对应的索引
target_indices = [num - 1 for num in target_elements]
result = [original_array[idx] for idx in target_indices]
print(result)
# 输出: [17, 19, 20, 21, 40, 45, 54, 65, 74, 77, 82]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:30:45