【发布时间】:2021-12-13 11:08:06
【问题描述】:
也许一些更有经验的人可以解释我的代码有什么问题。经过几个小时的调查,我放弃了! 我从 DB 获取对象列表(投资)。一些投资具有相同的“投资 ID”。 我想构建一个以“投资ID”为键的字典,并以列表中包含相同的“投资ID”作为值的投资 这是一个模拟投资类并构建测试列表的虚拟代码
class TestInvestment:
def __init__(self, id: str):
self.id = id
self.data = "bla...bla...bla"
def __repr__(self):
return f"Investment with code {self.id}"
test_investment1 = TestInvestment('RU000A100D89')
test_investment2 = TestInvestment('RU000A100YP2')
dummy_investments = [test_investment1, test_investment2]
这里是实际构建字典的函数。获取所有唯一 ID 作为一个集合,而不是基于该集合创建 dict,并将空列表作为值。最后将相应的投资附加到 dict 值。
def combine_investments(investments: List[TestInvestment]):
unique_investments_codes = set([investment.id for investment in investments])
unique_investments_dict = dict.fromkeys(unique_investments_codes, [])
[unique_investments_dict[investment.id].append(investment) for investment in investments]
return unique_investments_dict
但最后我得到了奇怪的结果。所有投资都添加到每个键中。
combined_investments = combine_investments(dummy_investments)
[print(item) for item in combined_investments.items()]
('RU000A100D89', [Investment with code RU000A100D89, Investment with code RU000A100YP2])
('RU000A100YP2', [Investment with code RU000A100D89, Investment with code RU000A100YP2])
我认为问题出在使用对象属性作为 dict 中的键的某个地方。但不确定…… 当我只是用完全相同的内容对字典进行硬编码时,一切都很完美!
def combine_investments(investments: List[TestInvestment]):
# unique_investments_codes = set([investment.id for investment in investments])
# unique_investments_dict = dict.fromkeys(unique_investments_codes, [])
unique_investments_dict = {'RU000A100D89': [], 'RU000A100YP2': []}
[unique_investments_dict[investment.id].append(investment) for investment in investments]
return unique_investments_dict
结果我得到了我想要的!
('RU000A100D89', [Investment with code RU000A100D89])
('RU000A100YP2', [Investment with code RU000A100YP2])
谁能指导我这种行为的原因是什么?
【问题讨论】:
标签: python python-3.x