如何将2个列表中的每个项目作为分数配对,直到所述列表结束?

时间:2014-09-17 13:58:23

标签: python list

鉴于以下两个清单:

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]

如何将它们附加到列表中以获得下面的结果?

c = [1/6, 1/7, 1/8, 1/9, 1/10, 2/6... 5/10]

2 个答案:

答案 0 :(得分:3)

使用map

>>> from fractions import Fraction
>>> a = [1, 2, 3, 4, 5]
>>> b = [6, 7, 8, 9, 10]
>>> map(Fraction, a, b)  # In Python 3.x: list(map(Fraction, a, b))
[Fraction(1, 6), Fraction(2, 7), Fraction(3, 8), Fraction(4, 9), Fraction(1, 2)]

您还可以使用zip

>>> [Fraction(x, y) for x, y in zip(a, b)]
[Fraction(1, 6), Fraction(2, 7), Fraction(3, 8), Fraction(4, 9), Fraction(1, 2)]

更新获取笛卡儿产品

使用列表推导(您可以使用多个for子句):

>>> [Fraction(x, y) for x in a for y in b]
[Fraction(1, 6), Fraction(1, 7), Fraction(1, 8), ....
 Fraction(5, 8), Fraction(5, 9), Fraction(1, 2)]

答案 1 :(得分:3)

使用itertools.product生成来自ab的数字对:

>>> import itertools
>>> from fractions import Fraction
>>> fracs = [Fraction(*pair) for pair in itertools.product(a, b)]
>>> fracs
[Fraction(1, 6), Fraction(1, 7), Fraction(1, 8), ... 
..., Fraction(5, 8), Fraction(5, 9), Fraction(1, 2)]

如果列表ab的长度不相等,这也有效。