![](/img/trans.png)
[英]How to find itertools product of tuples in a list of unknown length?
[英]How to find the product of elements in a multiple tuples in a list
我有以下清單:
list = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
如何返回包含元組中元素的乘積的列表,即:
[1, 2, 3, 2, 4, 6, 3, 6, 9]
在哪里
1*1 = 1 是新列表中的第一個元素
1*2 = 2 是新列表中的第二個元素
1*3 = 3 是新列表中的第三個元素
2*1 = 2 是新列表中的第 4 個元素
2*2 = 4 是新列表中的第 5 個元素
等等。
在列表理解中做到這一點的方法會很棒。 謝謝!
您可以使用列表理解:
from functools import reduce
from operator import mul
[reduce(mul, t, 1) for t in my_list]
不需要使用庫,一個簡單的列表理解就可以做到這一點:
lst = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
products = [a*b for a,b in lst]
# [1, 2, 3, 2, 4, 6, 3, 6, 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.