我有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由2.03(也对应值)。我想0在每个对应的元组位置的值都是偶数的情况下执行此操作,所以-2.50==-2.50等。显然,我们也为剩余元组做相同的数学运算。
0.49
1.91
first_lst
second_lst
0.52
2.03
0
-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]]
但是生成一些对象:
[<generator object <genexpr> at 0x0223E2B0>]
您能帮我解决代码吗?
您需要使用tuple()或list()将生成器表达式转换为list或tuple:
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)]