在 python 的字符串列表中查找字符串对我不起作用

Mil*_*nic 0 python loops

我已经在 python 上编写了一个更复杂的程序,但我一直试图找出列表是否包含给定的字符串。

简化问题:

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')
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这不起作用,我是否必须以某种方式重新启动起始索引,是这样,如何?

小智 5

改变

product_ids = (p['id'] for p in products)
Run Code Online (Sandbox Code Playgroud)

product_ids = [p['id'] for p in products]
Run Code Online (Sandbox Code Playgroud)

它应该工作。

您所做的是创建了一个生成器,该生成器将在您的第一个for循环后耗尽。改为使用方括号创建一个列表,该列表可以根据需要迭代多次。