简体   繁体   English

Python:将列表中的所有元素相乘,但先减去1

[英]Python: multiply all elements of a list but subtract 1 first

What is the most pythonic and elegant way to multiply the values of all elements of a list minus 1 together in Python? 在Python中将列表的所有元素的值减去1的最Python优雅方法是什么?

Ie, calculate (p[0]-1) * (p[1]-1) * ... * (p[n-1]-1) where n is the size of the list p. 即,计算(p [0] -1)*(p [1] -1)* ... *(p [n-1] -1),其中n是列表p的大小。

Use functools.reduce in python3 along with AJ's example: 在python3中使用functools.reduce和AJ的示例一起使用:

>>> l = [5, 8, 7, 2, 3]
>>> l = [item-1 for item in l] #subtract 1
>>> functools.reduce(lambda x, y: x*y, l) #multiply each item
336
>>> 

Using the numpy package 使用numpy

import numpy as np
np.prod(np.array(p)-1)

Or using a python built-in one, eg operator 或使用内置的python,例如operator

reduce(operator.mul,\ 
       map(lambda el:el-1,\
           p),\
       1)
>>> l = [5, 8, 7, 2, 3]
>>> reduce(lambda x, y: x*(y-1), l, 1) #multiply each item by its subtracted value
336
>>> 

Thanks to @AChampion for another improvement 感谢@AChampion的另一个改进

There are many ways to multiply all the elements of an iterable. 有很多方法可以将可迭代的所有元素相乘。

So, given a list a you can, for example: 所以,对于一个列表a就可以了,例如:

Use numpy: 使用numpy:

prod([x-1 for x in a])

Use lambda and functools 使用lambda和functools

functools.reduce(lambda x, y: x*y, [x-1 for x in a])

Do it manually 手动执行

result=1
for x in [x-1 for x in a]: result*=a 

Note that I used the list comprehension: [x-1 for x in a] but it can also be achieved with numpy: array(a)-1 请注意,我使用了列表推导: [x-1 for x in a]但也可以使用numpy实现: array(a)-1


Related question: What's the Python function like sum() but for multiplication? 相关问题: 类似于sum()的Python函数是什么? product()? 产品()?

result = 1
for x in p:
    result *= x - 1

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

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