鉴于以下两个清单:
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]
答案 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
生成来自a
和b
的数字对:
>>> 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)]
如果列表a
和b
的长度不相等,这也有效。