有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')]
>>> [((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]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'fir' is not defined
>>>
并<generator object <genexpr>
提到了消息。
1) 让我们通过创建列表理解以最少的更改来修复代码:
>>> 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')]
>>> [(fir[0],fir[1]*float(sec[1]),fir[2]*float(sec[2])) for fir in first_lst for sec in second_lst if fir[0] == sec[0]] # list comprehension
[('-2.50', 0.9359, 1.0555999999999999), ('-2.00', 0.9516000000000001, 1.04)]
>>>
2)在原始代码中,后面的括号first_lst
)
放错了位置。如果我们将括号放在sec[0]
而不是列表推导之后,我们会得到生成器表达式。这将导致<generator object <genexpr>
消息:
>>> [((fir[0],fir[1]*float(sec[1]),fir[2]*float(sec[2])) for fir in first_lst for sec in second_lst if fir[0] == sec[0])] # generator object
[<generator object <genexpr> at 0x00000184EEDE29E8>]
在语法方面,唯一的区别是使用括号而不是方括号。
注意:如果需要,有两种方法可以将生成器对象转换为列表:
2a) 使用星号 (*) 运算符将对象解包到列表中
>>> [*((fir[0],fir[1]*float(sec[1]),fir[2]*float(sec[2])) for fir in first_lst for sec in second_lst if fir[0] == sec[0])]
[('-2.50', 0.9359, 1.0555999999999999), ('-2.00', 0.9516000000000001, 1.04)]
>>>
2b) 明确使用list()
>>> list((fir[0],fir[1]*float(sec[1]),fir[2]*float(sec[2])) for fir in first_lst for sec in second_lst if fir[0] == sec[0])
[('-2.50', 0.9359, 1.0555999999999999), ('-2.00', 0.9516000000000001, 1.04)]
>>>