乘以两个列表的所有组合 [英] Multiply all combinations of two lists

查看:71
本文介绍了乘以两个列表的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想知道如何从两个列表中提取所有元素并彼此相乘.例如,如果有两个列表

I really want to know how to extract all the element from two lists and multiply each other. For example, if there are two lists

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

我想做1X2、1X4、1X6、1x8、3x2等 来自A X的一个元素来自B的一个元素. 我尝试使用zip,但由于长度不同,我无法获得正确的答案.

I want to do 1X2, 1X4, 1X6, 1x8, 3x2... etc. One element from A X one element from B. I tried to use zip but because of length difference, I couldn't get right answers.

推荐答案

由于您的问题似乎需要两个列表之间的笛卡尔积,因此可以使用

SInce your question seems to want the cartesian product between two lists, you can use itertools.product to bind every element from A with every element from B:

>>> from itertools import product
>>> A = [1,3,5,7,9]
>>> B = [2,4,6,8]
>>> list(product(A, B))
[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8), (9, 2), (9, 4), (9, 6), (9, 8)]

然后,如果要将每个元组中的两个元素相乘,则可以执行以下操作:

Then if you want to multiply the the two elements in each tuple, you can do this:

>>> [x * y for x, y in product(A, B)]
[2, 4, 6, 8, 6, 12, 18, 24, 10, 20, 30, 40, 14, 28, 42, 56, 18, 36, 54, 72]

这篇关于乘以两个列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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