简体   繁体   中英

How to conditionally append tuples from one list to another list of tuples?

I have two lists 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)]

What I want to achieve is this. If the first part of a tuple (Debt collection, Mortgage, etc.) exists in lst2 but not in lst1, I want to append a new tuple to lst1 in the format of

(non-existent tuple, 0)

So ideally I want lst1 to look like this:

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)]

I've been thinking that the easiest way to achieve this would be through a list comprehension where I append the result to lst1.

List comprehension:

lst1.append((tpl[0],0) for tpl in \
lst1 for tpl1 in lst2 if tpl1[0] not in tpl)

However when I look at the results I get the following:

[('Debt collection', 5572),
 ('Mortgage', 4483),
 ('Credit reporting', 3230),
 ('Checking or savings account', 2068),
 ('Student loan', 431),
 <generator object <genexpr> at 0x12bc68780>]

How would I go about turning the generator object into something I can actually see when printing lst1? Is what I want to achieve here even possible?

You need to extract from generator object and use extend . Also the loop order in your list comprehension is incorrect and will yield you a wrong output even if you had extracted.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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