Python映射函数是返回值的函数吗? [英] Is the Python map function a value-returning function?

查看:91
本文介绍了Python映射函数是返回值的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Python中的map函数,并且在使用它时遇到了一些麻烦.我不知道其中哪一种是将函数foo映射到列表栏的正确方法:

I've been trying to work with the map function in Python, and I've been having a little bit of trouble with it. I can't tell which of these is the proper way to map function foo to the list bar:

map(foo, bar)

newBar = map(foo, bar)

我从不同的网站获得了不同的结果.哪个是正确的用法?

I'm getting varied results from different websites. Which of these is the correct usage?

推荐答案

在Python 2中,

In Python 2, map() returns a list of return values of foo(...). If you don't care about the results and just want to run the elements of bar through foo, either of your examples will work.

在Python 3中, map() 返回的迭代器为懒洋洋地评价.您的两个示例都不会实际运行barfoo 的任何元素.您将需要迭代该迭代器.最简单的方法是将其转换为列表:

In Python 3, map() returns an iterator that is evaluated lazily. Neither of your examples will actually run any elements of bar through foo yet. You will need to iterate over that iterator. The simplest way would be to convert it to a list:

list(map(foo, bar))

这篇关于Python映射函数是返回值的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆