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

Python中如何基于数组索引截取列表?实操问题求助

How to Extract List Elements Using Numpy Array Indices

It looks like you're trying to pull specific elements from your list using indices stored in a numpy array, but your current code has a couple of issues that are preventing it from working as expected. Let's break down what's going wrong and fix it.

What's Wrong With Your Current Code

  1. Undefined Variable: You reference X but haven't defined it—this is likely a typo for your vars list.
  2. Incorrect Index Check: Your new_L is a tuple containing a numpy array (like (array([1,5,7]),)), so checking if i in new_L is looking for the index in the tuple itself, not the array inside it.
  3. No Collection of Results: You're just printing indices instead of gathering the corresponding elements from your list.
    Side note: It's best to avoid using vars as a variable name since it's a built-in Python function. I've renamed it to vars_list in the examples below to prevent any conflicts.

Simple Solutions to Get Your Desired Output

First, let's set up your original variables properly and extract the actual indices array from the tuple:

import numpy as np

# Your original list of column names
vars_list = ['age','balance','day','duration','campaign','pdays','previous','job_admin.','job_blue-collar']
# Your indices wrapped in a tuple
new_L = (np.array([1, 5, 7], dtype=int64),)

# Extract the indices array from the tuple
indices = new_L[0]

Solution 1: List Comprehension (Most Pythonic)

This is the cleanest and most readable way to get your desired list:

result = [vars_list[i] for i in indices]
print(result)  # Output: ['balance','pdays','job_admin.']

Solution 2: Using Numpy Array Indexing

If you prefer working with numpy, convert your list to a numpy array and index directly:

vars_array = np.array(vars_list)
result = vars_array[indices].tolist()
print(result)  # Same output as above

Solution 3: Fixed Loop Approach

If you want to stick with a loop, here's how to adjust your code to collect the correct elements:

result = []
for i in indices:
    result.append(vars_list[i])
print(result)

All three methods will give you the exact output you're looking for. The list comprehension is generally the most efficient and idiomatic choice for this kind of task.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:10:09