python - 在 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')
我不明白为什么这不起作用,我是否必须以某种方式重新启动起始索引,是这样,如何?
解决方案
改变
product_ids = (p['id'] for p in products)
到
product_ids = [p['id'] for p in products]
它应该可以工作。
您所做的是创建了一个生成器,该生成器将在您的第一个for
循环后耗尽。改为方括号会创建一个列表,可以根据需要多次迭代。
推荐阅读
- sql - SQL Server - 当 sql server 和应用程序在同一台服务器上时,关闭外部端口并作为 localhost 工作
- oracle - Oracle:使用“立即执行”和行数删除行
- sql - 使用 CASE 为 SQLite 中的 COUNT 语句设置条件
- c# - 覆盖 ASP .NET/EFCore 3.0 中未调用的 SaveChanges()
- sql - 检查表中是否存在作为参数给出的 oracle 函数值
- css - React 应用程序 - 避免样式被其他 CSS 覆盖
- node.js - 如何等到所有嵌套函数都执行完
- excel - 跨多个工作表查找公式
- python - django.core.exceptions.ValidationError: ["'_auth_user_id' value must be an integer."] Django 错误
- vim - Unexpected SPACE character while in : 在 Neovim 中按减号键 (-) 时探索