【发布时间】:2019-01-19 17:25:47
【问题描述】:
我有两个元组列表。
lst1 = [('Debt collection', 5572),
('Mortgage', 4483),
('Credit reporting', 3230),
('Checking or savings account', 2068),
('Student loan', 431)]
lst2 = [('Consumer Loan', 480),
('Student loan', 1632),
('Medical loan', 1632),
('Vehicle loan or lease', 377),
('Money transfer, virtual currency, or money service', 248),
('Payday loan, title loan, or personal loan', 245),
('Prepaid card', 83)]
我想要实现的是这个。如果元组的第一部分(债务收集、抵押等)存在于 lst2 但不在 lst1 中,我想以
的格式将新元组附加到 lst1(non-existent tuple, 0)
所以理想情况下,我希望 lst1 看起来像这样:
lst1 = [('Debt collection', 5572),
('Mortgage', 4483),
('Credit reporting', 3230),
('Checking or savings account', 2068),
('Student loan', 431),
('Consumer Loan', 0),
('Medical Loan', 0),
('Vehicle loan or lease', 0),
('Money transfer, virtual currency, or money service', 0),
('Payday loan, title loan, or personal loan', 0),
('Prepaid card', 0)]
我一直认为实现这一目标的最简单方法是通过列表理解,将结果附加到 lst1。
列表理解:
lst1.append((tpl[0],0) for tpl in \
lst1 for tpl1 in lst2 if tpl1[0] not in tpl)
但是,当我查看结果时,我得到以下结果:
[('Debt collection', 5572),
('Mortgage', 4483),
('Credit reporting', 3230),
('Checking or savings account', 2068),
('Student loan', 431),
<generator object <genexpr> at 0x12bc68780>]
如何将生成器对象变成打印 lst1 时可以实际看到的东西?我想在这里实现的目标有可能吗?
【问题讨论】: