我有两个元组列表。
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时,如何将生成器对象变成实际上可以看到的东西?我想在这里实现什么甚至可能?
答案 0 :(得分:0)
您需要从生成器对象中提取并使用extend
。同样,列表理解中的循环顺序是不正确的,即使您已提取,也会产生错误的输出。
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)]
available = [tpl[0] for tpl in lst1]
lst1.extend(tuple((tpl1[0], 0) for tpl1 in lst2 if tpl1[0] not in available))
print(lst1)