首页 > 解决方案 > 在 python 中的字符串列表中查找字符串对我不起作用

问题描述

我在 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')

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

标签: pythonloops

解决方案


改变

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

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

它应该可以工作。

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


推荐阅读