简体   繁体   English

在python中将一个整数列表的子集相乘

[英]Multiplying a subset of a list of integers together in python

Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. 假设我有一个10个整数的列表,我想要将前5个乘以的结果。 Is there a pythonic way of doing this? 有这样做的pythonic方式吗? Python seems to be great with lists :) Python似乎很棒的列表:)

import operator
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print reduce(operator.mul, [v for (k, v,) in enumerate(l) if k < 5])
>> 120

Edit: Better way to do it 编辑:更好的方式来做到这一点

print reduce(operator.mul, l[:5])
>> 120

Lot's of ways. 很多方法。 Here's one: 这是一个:

>>> a = range(1,10)
>>> reduce(lambda x,y: x*y, a[:5])
120

When there are many ways to do something, I turn to criteria such as readability or speed to decide which code to use. 当有很多方法可以做某事时,我会转向可读性或速度等标准来决定使用哪种代码。 Here is some code which suggests that use_loop and use_reduce are roughly tied in terms of speed (at least for the values tested!) 这里有一些代码表明use_loopuse_reduce在速度方面大致相关(至少对于测试的值!)

import operator
import itertools

a=range(1,1000)
def use_loop(a,n):
    result=1
    for num in a[:n]:
        result*=num
    return result

def use_reduce(a,n):
    return reduce(operator.mul, a[:n])

def use_reduce_lambda(a,n):
    return reduce(lambda x,y: x*y, a[:n])

def use_islice_loop(a,n):
    result=1
    for num in itertools.islice(a,n):
        result*=num
    return result

def use_islice_reduce(a,n):
    return reduce(operator.mul, itertools.islice(a,n))

if __name__=='__main__':
    n=50
    print(use_loop(a,n))
    print(use_reduce(a,n))
    print(use_reduce_lambda(a,n))    
    print(use_islice_loop(a,n))
    print(use_islice_reduce(a,n))    

Here are the timing results: 以下是时间结果:

% python -mtimeit -s"import test" "test.use_loop(test.a,50)"
10000 loops, best of 3: 16.1 usec per loop
% python -mtimeit -s"import test" "test.use_reduce(test.a,50)"
100000 loops, best of 3: 16.3 usec per loop
% python -mtimeit -s"import test" "test.use_islice_loop(test.a,50)"
10000 loops, best of 3: 19.6 usec per loop
% python -mtimeit -s"import test" "test.use_islice_reduce(test.a,50)"
10000 loops, best of 3: 19.2 usec per loop
% python -mtimeit -s"import test" "test.use_reduce_lambda(test.a,50)"
10000 loops, best of 3: 32.1 usec per loop

At least for the value of a (1000) and n (50) tested, itertools.islice did not seem to help performance. 至少对于测试a (1000)和n (50)的值, itertools.islice似乎没有帮助性能。 use_reduce_lambda was significantly slower than it's cousin use_reduce , which used operator.mul . use_reduce_lambda明显慢于使用operator.mul的表兄use_reduce The time required to import operator was not included in the test, however. 但是,导入operator所需的时间不包括在测试中。

Since use_loop and use_reduce seem equally fast, I'd suggest using reduce since its short, idiomatic code should be quite readable to most python programmers. 由于use_loopuse_reduce似乎同样快,我建议使用reduce因为它的简短,惯用的代码应该对大多数python程序员来说都是可读的。 However, in matters of taste I don't think it pays to be too opinionated. 然而,在品味问题上,我认为过于自以为是不值得。 Choose what you like best, just be consistent. 选择你最喜欢的,只要保持一致。

PS. PS。 As of Python 3+, reduce is no longer a built-in function, but can be accessed through functools.reduce . 从Python 3+开始, reduce不再是内置函数,但可以通过functools.reduce访问。

This is a simple function that will do what you want. 这是一个简单的功能,可以做你想要的。

def multiply(args):
    x= 1
    for arg in args:
       x*= arg
    return x

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

multiply(l)
>>>362880
multiply(l[:5])
>>>120

Using reduce: 使用reduce:

reduce(lambda x, y: x*y, mylist[:5])

eg, 例如,

>>> reduce(lambda x,y:x*y, range(1,5))
24

the reduce() function applies the given function (here, multiplication) over the first two items of the list, hereby reducing them to one item. reduce()函数将给定函数(此处为乘法)应用于列表的前两项,从而将它们减少为一个项目。 This is done until there is only one item in the list. 这样做直到列表中只有一个项目。 This item is returned as the result. 此项目作为结果返回。 This notation is derived from functional languages. 此表示法源自函数语言。

Iterating through the list: 迭代列表:

result=1
for i in mylist[:5]:
    result*=i

eg, 例如,

>>> result=1
>>> for i in range(1,5):
    result*=i
>>> result
24

This is the most general way of aggregating some function over all items of a list; 这是在列表的所有项目上聚合某些功能的最常用方法; It is similar to the way this would have been done Java or C. 它类似于Java或C的方式。

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

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