簡體   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