Python中如何基于数组索引截取列表?实操问题求助
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
- Undefined Variable: You reference
Xbut haven't defined it—this is likely a typo for yourvarslist. - Incorrect Index Check: Your
new_Lis a tuple containing a numpy array (like(array([1,5,7]),)), so checkingif i in new_Lis looking for the index in the tuple itself, not the array inside it. - 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 usingvarsas a variable name since it's a built-in Python function. I've renamed it tovars_listin 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

