简体   繁体   English

在 python 中使用 functools.reduce 时是否有在可迭代对象中获取值索引

[英]is there anyway of getting a values index in an iterable when using functools.reduce in python

I have a function that would benefit from using functools.reduce it would act something like this我有一个 function 可以从使用 functools.reduce 中受益,它会像这样

import functools

def add(total, val, max_index, index):
    if index > max_index:
        return total
    else:
        return total + val

arr = [1,2,3,4,5,6,7,8]
functools.reduce(functools.partial(add, max_index=5), arr, 0)

how do I pass the index of the val in the arr into the function or is it just not possible I thought about using a global variable to track the index but of course would much rather not如何将arrval的索引传递给 function 或者我是否不可能考虑使用全局变量来跟踪索引,但当然宁愿不

by the way my function is meant to be used for an array a lot larger than an array of len 8顺便说一句,我的 function 用于比 len 8 数组大很多的数组

You could always pass enumerate(arr) which transforms any iterable of elements X_i into another of elements (i,X_i) .您始终可以传递enumerate(arr) ,它将任何可迭代的元素 X_i 转换为另一个元素(i,X_i)

Then the function would need to unpack the "value" it received (which is now a 2-tuple) into index and value.然后 function 需要将它收到的“值”(现在是一个 2 元组)解压缩为索引和值。

Example:例子:

import functools

def add(total, index_val, max_index):
    index, val = index_val
    if index > max_index:
        return total
    else:
        return total + val

arr = [1,2,3,4,5,6,7,8]
res = functools.reduce(functools.partial(add, max_index=5), enumerate(arr,0), 0)
print(res)

Python reduce function is removed from global namespace to functools and general instruction is to use list comprehension instead. Python reduce function 从全局命名空间中删除到 functools,一般指令是使用列表推导。 Using list-comprehensions I would do it like this:使用列表理解我会这样做:

arr = [1,2,3,4,5,6,7,8]
max_index = 5
# 0-based index
print( sum([val for index, val in enumerate(arr,0) if index<=max_index]) )
# output is 21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM