问题
I try this:
def test(x):
return x**2
a = map(test,[1,2,3])
If I get the value like this:
for i in a:
print(a)
I will get 1,4,9 and this works perfectly.
But if I do this: a[0]. The error will be raised.
I know it is because the result of map function is map class:
type(map(test,[1,2,3])) == <class 'map'>
which is not subsciptable.
So how can I use the index to get the value of the result of map function?
NOTE: This behavior is specific to python 3.
回答1:
Convert the map object into a list object:
a = list(map(test,[1,2,3]))
Then you can use list indices to access the individual elements.
回答2:
The built-in map() function in python 3 returns an iterator. Once you consume an iterator or it is exhausted, it won't yield you result any more.
a = map(lambda x: x**2, [1,2,3])
for i in a: print(a)
The result:
1
4
9
Now try,
a.__next__()
It will return you a StopIteration error, as the iterator is already exhausted.
To use index you can use list as suggested in the previous answer.
来源:https://stackoverflow.com/questions/37110086/how-to-use-index-to-get-the-value-from-the-result-of-map-function-by-python-3