Python 3: apply an operator over an iterable

不羁的心 提交于 2019-12-10 20:09:24

问题


sum(iterable) is effectively:

def sum(iterable):
    s = 0
    for x in iterable:
        s = s.__add__(x)
    return s

Does Python have a built-in function that accomplishes this without setting the initial value?

# add is interchangeable with sub, mul, etc.
def chain_add(iterable):
    iterator = iter(iterable)
    s = next(iterator)
    while True:
        try:
            s = s.__add__(next(iterator))
        except StopIteration:
            return s

The problem I have with sum is that it does not work for other types that support the + operator, e.g. Counter.


回答1:


Try looking into the python reduce() function: You pass in a function, an iterable, and an optional initializer and it would apply the function cumulatively to all the values.

For example:

import functools
def f(x,y):
    return x+y

print functools.reduce(f, [1, 2, 3, 4]) # prints 10
print functools.reduce(f, [1, 2, 3, 4], 10) # prints 20, because it initializes at 10, not 0.

You can change the function based on your iterable, so it's very customizable.




回答2:


In the case of addition:

import operator
reduce(operator.add, iterable)

This will work on iterables that can't be added together using sum. Similarly, you could perform multiplication using

reduce(operator.mul, iterable)



回答3:


This is a pretty good use for reduce(), which was moved to functools.reduce() in Python 3.

Here is an example for chaining multiplication:

import functools
import operator

def chain_mul(iterable):
    return functools.reduce(operator.mul, iterable)

You can replace operator.mul there with one of the other functions from the operator module, or just define your own two-argument function that operates on its arguments.



来源:https://stackoverflow.com/questions/11961950/python-3-apply-an-operator-over-an-iterable

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