获取<generator object <genexpr>

nut*_*hip 8 python list-comprehension python-2.7

我有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')]
Run Code Online (Sandbox Code Playgroud)

我想对它做以下数学运算:

乘以0.491.91(从相应的值first_lstsecond_lst)和乘0.522.03(对应值也).我希望这样做,条件是0每个相应元组中位置的值是理想的,所以-2.50== -2.50等.显然,我们也做同样的数学运算重组元组.

我的代码:

[((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]]
Run Code Online (Sandbox Code Playgroud)

然而产生一些对象:

[<generator object <genexpr> at 0x0223E2B0>]
Run Code Online (Sandbox Code Playgroud)

你能帮我解决一下代码吗?

Ash*_*ary 14

您需要使用tuple()list()将该生成器表达式转换为listtuple:

[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]]
Run Code Online (Sandbox Code Playgroud)

代码的工作版本:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)