Python 3.6.3中用map处理numpy数组遇TypeError问题求助
Let's break down what's happening in your code and how to fix it:
Why the Error Occurs
Your seen variable is a 2D numpy array (shape (3,1)):
seen = np.array([[0,1,0]]).T # Output: array([[0], # [1], # [0]])
When map iterates over seen, each x passed to the lambda is a 1-element numpy array (like array([0])), not a plain integer. Python lists (like observations) only accept integer scalars as indices—you can't use an array to index into a list, hence the error.
How to Fix It
You have a few straightforward solutions:
1. Flatten the seen Array
Convert the 2D array to a 1D array so each iteration gives an integer scalar:
import numpy as np observations = ["red", "white"] seen = np.array([[0,1,0]]).T # Use flatten() to get a 1D array result = list(map(lambda x: observations[x], seen.flatten())) print(result) # Output: ['red', 'white', 'red']
2. Extract the Scalar from Each Array Element
Modify your lambda to pull the integer value out of the 1-element array:
result = list(map(lambda x: observations[x[0]], seen)) print(result) # Output: ['red', 'white', 'red']
3. Use Numpy's Built-in Indexing (More Idiomatic)
Since you're already using numpy, skip map entirely and use numpy's native array indexing:
# Convert observations to a numpy array first, then index numpy_obs = np.array(observations) result = numpy_obs[seen.flatten()].tolist() # Or directly handle the 2D array: result = numpy_obs[seen].flatten().tolist() print(result) # Output: ['red', 'white', 'red']
How to View Map Results
The map object you see (<map at 0x2ab8c869e80>) is an iterator—it doesn't compute results until you iterate over it. To see the actual values, convert it to a list with list(map(...)) (which is what you were trying to do, but the error stopped you). Once you fix the indexing issue, this will work as expected.
内容的提问来源于stack exchange,提问作者Sunny

