我可以在 map 函数中使用索引信息吗? [英] Can I use index information inside the map function?

查看:55
本文介绍了我可以在 map 函数中使用索引信息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个列表 a = [1, 3, 5, 6, 8].

我想在该列表上应用一些转换,我想避免按顺序进行,所以像 map(someTransformationFunction, a) 之类的东西通常可以解决问题,但是如果转换需要知道每个对象的索引吗?

例如,假设每个元素必须乘以其位置.所以列表应该转换为 a = [0, 3, 10, 18, 32].

有没有办法做到这一点?

解决方案

使用 enumerate() 添加索引的函数:

map(function, enumerate(a))

您的函数将被传递一个元组,带有(index, value).在 Python 2 中,您可以在函数签名中指定 Python 为您解包元组:

map(lambda (i, el): i * el, enumerate(a))

注意 lambda 参数规范中的 (i, el) 元组.您可以在 def 语句中执行相同的操作:

def mapfunction((i, el)):返回 i * el地图(地图功能,枚举(a))

为了让其他函数签名功能(如注解)让位,函数参数中的元组解包已从 Python 3 中删除.

演示:

<预><代码>>>>a = [1, 3, 5, 6, 8]>>>def mapfunction((i, el)):... 返回 i * el...>>>地图(拉姆达(我,el):我* el,枚举(a))[0, 3, 10, 18, 32]>>>地图(地图功能,枚举(a))[0, 3, 10, 18, 32]

Let's assume there is a list a = [1, 3, 5, 6, 8].

I want to apply some transformation on that list and I want to avoid doing it sequentially, so something like map(someTransformationFunction, a) would normally do the trick, but what if the transformation needs to have knowledge of the index of each object?

For example let's say that each element must be multiplied by its position. So the list should be transformed to a = [0, 3, 10, 18, 32].

Is there a way to do that?

解决方案

Use the enumerate() function to add indices:

map(function, enumerate(a))

Your function will be passed a tuple, with (index, value). In Python 2, you can specify that Python unpack the tuple for you in the function signature:

map(lambda (i, el): i * el, enumerate(a))

Note the (i, el) tuple in the lambda argument specification. You can do the same in a def statement:

def mapfunction((i, el)):
    return i * el

map(mapfunction, enumerate(a))

To make way for other function signature features such as annotations, tuple unpacking in function arguments has been removed from Python 3.

Demo:

>>> a = [1, 3, 5, 6, 8]
>>> def mapfunction((i, el)):
...     return i * el
...
>>> map(lambda (i, el): i * el, enumerate(a))
[0, 3, 10, 18, 32]
>>> map(mapfunction, enumerate(a))
[0, 3, 10, 18, 32]

这篇关于我可以在 map 函数中使用索引信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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