我有 2 个列表:
first_lst = [('-2.50', 0.49, 0.52), ('-2.00', 0.52, 0.50)]
second_lst = [('-2.50', '1.91', '2.03'), ('-2.00', '1.83', '2.08')]
我想对其进行以下计算:
将0.49
乘以1.91
(first_lst
和second_lst
的对应值),然后乘以 0.52
by 2.03
(也有相应的值)。我想在每个相应元组中位置 0
的值相同的条件下执行此操作,因此 -2.50
== -2.50
等。显然,我们也对 remaning 元组进行相同的计算。
我的代码:
[((fir[0], float(fir[1])*float(sec[1]), float(fir[2])*float(sec[2])) for fir in first_lst) for sec in second_lst if fir[0] == sec[0]]
然而生成一些对象:
[<generator object <genexpr> at 0x0223E2B0>]
你能帮我修改代码吗?
最佳答案
您需要使用 tuple()
或 list()
将该生成器表达式转换为 list
或 tuple
:
[tuple((fir[0], fir[1]*sec[1], fir[2]*sec[2]) for fir in first_lst)\
for sec in second_lst if fir[0] == sec[0]]
代码的工作版本:
>>> first_lst = [tuple(float(y) for y in x) for x in first_lst]
>>> second_lst = [tuple(float(y) for y in x) for x in second_lst]
>>> [((fir[0],) + tuple(x*y for x, y in zip(fir[1:], sec[1:]))) \
for fir in first_lst for sec in second_lst if fir[0]==sec[0]]
[(-2.5, 0.9359, 1.0555999999999999), (-2.0, 0.9516000000000001, 1.04)]
关于python - 获取<生成器对象<genexpr>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16373484/