How to use index to get the value from the result of map function by Python 3?

限于喜欢 提交于 2021-02-11 09:55:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!