如何使用 Python 从另一个列表中按列表项划分列表项?
How to divide list item by list item from another list using Python?
我想在两个列表中划分列表项。
a = [[1, 0, 2], [0, 0, 0], [1], [1]]
b = [[5, 6, 4], [6, 6, 6], [3], [3]]
如何将 a 除以 b 以获得此输出:
c = [[0.2, 0, 0.5], [0, 0, 0], [0.333], [0.333]]
谁能帮帮我?
压缩两个列表并使用列表理解:
from __future__ import division # in python2 only
result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
样本运行:
In [1]: a = [[1, 0, 2], [0, 0, 0], [1], [1]]
...: b = [[5, 6, 4], [6, 6, 6], [3], [3]]
...:
In [2]: result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
In [3]: result
Out[3]: [[0.2, 0.0, 0.5], [0.0, 0.0, 0.0], [0.3333333333333333], [0.3333333333333333]]
使用 itertools.izip
(Python2.7):
import itertools
[[float(aaa) / bbb for (aaa, bbb) in itertools.izip(aa, bb)] \
for (aa, bb) in itertools.izip(a, b)]
from __future__ import division # for Python2
[[x / y for x, y in zip(*item)] for item in zip(a, b)]
我想在两个列表中划分列表项。
a = [[1, 0, 2], [0, 0, 0], [1], [1]]
b = [[5, 6, 4], [6, 6, 6], [3], [3]]
如何将 a 除以 b 以获得此输出:
c = [[0.2, 0, 0.5], [0, 0, 0], [0.333], [0.333]]
谁能帮帮我?
压缩两个列表并使用列表理解:
from __future__ import division # in python2 only
result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
样本运行:
In [1]: a = [[1, 0, 2], [0, 0, 0], [1], [1]]
...: b = [[5, 6, 4], [6, 6, 6], [3], [3]]
...:
In [2]: result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
In [3]: result
Out[3]: [[0.2, 0.0, 0.5], [0.0, 0.0, 0.0], [0.3333333333333333], [0.3333333333333333]]
使用 itertools.izip
(Python2.7):
import itertools
[[float(aaa) / bbb for (aaa, bbb) in itertools.izip(aa, bb)] \
for (aa, bb) in itertools.izip(a, b)]
from __future__ import division # for Python2
[[x / y for x, y in zip(*item)] for item in zip(a, b)]