我觉得这可以在一行中完成,但我找不到办法。这可以在python中的一行中完成吗?
# final_list is what I want as an output
final_list = []
for x in some_list:
# y is a dictionary
y = x.get_some_dict()
# Want to add a new key/value pair to y, which comes from x
y.update({"new_key": x.property_in_x})
# append y to the output list
final_list.append(y)
return final_list
我认为更好的问题是为什么你要完全取好的代码并将其塞进一个可能不可读的行中。 – csmckelvey
由于'dict.update'这样做会在一行中做到这一点很棘手,并且如上所述可能不太容易理解 – jonrsharpe
不要陷入思考一个线程为更好的代码所思考的陷阱。这段代码非常好,没有理由被塞进一行。 –