Python 3:在可迭代项上应用运算符 [英] Python 3: apply an operator over an iterable

查看:88
本文介绍了Python 3:在可迭代项上应用运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sum(iterable)有效:

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

Python是否有一个内置函数可以在不设置初始值的情况下完成此任务?

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

sum的问题是它不适用于支持+运算符的其他类型,例如Counter.

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

推荐答案

尝试查看python reduce()函数:您传入一个函数,一个可迭代的函数和一个可选的初始化器,它将对所有值累积应用该函数.

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.

例如:

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.

这篇关于Python 3:在可迭代项上应用运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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