获取< generator对象< genexpr> [英] Getting <generator object <genexpr>
问题描述
我有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')]
我想对它做以下数学运算:
I want to do the following math to it:
将0.49
乘以1.91
(对应于first_lst
和second_lst
的值),然后将0.52
乘以2.03
(也对应相应的值).我想在每个对应元组的位置0
上的值都是偶数的情况下执行此操作,因此-2.50
== -2.50
等.显然,我们还对剩余元组进行了相同的数学运算.
Multiply 0.49
by 1.91
(the corresponding values from first_lst
and second_lst
), and multiply 0.52
by 2.03
(corresponding values also). I want to do that under condition that values at position 0
in each corresponding tuple is idential so -2.50
== -2.50
etc. Obviously, we do the same math for remaning tuples as well.
我的代码:
[((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>]
您能帮我解决代码吗?
Can you help me fix the code?
推荐答案
您需要使用tuple()
或list()
将该生成器表达式转换为list
或tuple
:
You need to use tuple()
or list()
to convert that generator expression to a list
or 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)]
这篇关于获取< generator对象< genexpr>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!