将内部列表元素相乘作为列表推导式

5
这可以使用列表推导式在一行中完成吗?
lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
products = ?? (Multiple each list elements)

期望输出:[6, 24, 30, 9]

我尝试了以下代码:

products = [l[i] * l[i + 1] for l in lst for i in range(len(l) - 1)]

但是没有成功。

你是否也需要知道为什么你的方法没有起作用的答案? - Bhargav Rao
6个回答

9
你可以使用 reduce() 函数将乘法应用于整数列表,结合使用 operator.mul() 函数进行实际的乘法操作:
from functools import reduce

from operator import mul

products = [reduce(mul, l) for l in lst]

在Python 3中,reduce()已经被移动到functools.reduce(),因此需要相应的import语句。由于functools.reduce自Python 2.6以来就存在,如果您需要使您的代码与Python 2和3兼容,则从那里导入它会更加简单。
演示:
>>> from operator import mul
>>> lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
>>> [reduce(mul, l) for l in lst]
[6, 24, 30, 9]

operator.mul() 可以被替换为 lambda x, y: x * y,但是何必自己把事情复杂化呢?


点赞 mul,我也想到了用 lambda 的相同答案,这更好。 - miradulo

3

使用numpy的另一种方法。

>>> from numpy import prod
>>> [prod(x) for x in lst] 
[6, 24, 30, 9]

参考资料 - 有关prod的文档


1

尝试:

products = [reduce(lambda x, y: x * y, l) for l in lst]

1

是的,您可以在列表推导式中使用reduce和lambda表达式:

>>> [reduce(lambda x, y: x * y, innerlst) for innerlst in lst]
[6, 24, 30, 9]

注意,在Python 3中,reduce已经被移动到functools模块中,因此您必须从那里导入它: from functools import reduce 如果您不想使用lambda表达式,可以完全用operator.mul替换。

1
使用this解决方案,使列表拥有产品运营商的功能,您可以执行以下操作:
    lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
    import operator
    from functools import reduce # Valid in Python 2.6+, required in Python 3
    def prod(numeric_list):
        return reduce(operator.mul, numeric_list, 1)

    [prod(l) for l in lst]

输出:
    Out[1]: [6, 24, 30, 9]

0

开始使用 Python 3.8,并添加了 prod 函数到 math 模块中:

import math

# lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9], []]
[math.prod(l) for l in lst]
# [6, 24, 30, 9, 1]

请注意,空的子列表将获得一个乘积值为1,这是由start的值定义的:

math.prod(iterable, *, start=1)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接