【问题标题】:How to conditionally append tuples from one list to another list of tuples?如何有条件地将一个列表中的元组附加到另​​一个元组列表?
【发布时间】: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 时可以实际看到的东西?我想在这里实现的目标有可能吗?

【问题讨论】:

    标签: python list tuples


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2018-01-11
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      相关资源
      最近更新 更多