繁体   English   中英

如何有条件地将一个列表中的元组追加到另一个元组列表中?

[英]How to conditionally append tuples from one list to another list of tuples?

我有两个元组列表。

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时,如何将生成器对象变成实际上可以看到的东西? 我想在这里实现的目标是否可能?

您需要从生成器对象中提取并使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM