简体   繁体   中英

Finding a string in list of strings in python is not working for me

I have written a more complex program on python, but I'm stuck on trying to find out if a list contains a given string.

Simplified problem:

product_names = ['string1', 'string2']
products = [{'id': 'string1', 'test': 'test1 - value'}, {'id': 'string3', 'test': 'test2 - value'}]

# prints: string1 string3
product_ids = (p['id'] for p in products)
for ids in product_ids:
    print(ids)

# doesn't print found
for p in product_names:
    if p in product_ids:
        print('found')
        
# doesn't print missing product names
if not all(p in product_ids for p in product_names):
    print('missing product names')

I don't get why this doesn't work, do I have to restart the starting index somehow, and is so, how?

Change

product_ids = (p['id'] for p in products)

to

product_ids = [p['id'] for p in products]

and it should work.

What you have done is created a generator which will be exhausted after your first for loop. Changing to square brackets instead creates a list which can be iterated over as many times as you want.

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