python - 演变一个 for 循环以跳过不等于的 dict 键和值
问题描述
背景
我的结构如下:
trash = [ {'href': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'},
{'href': 'https://www.simplyrecipes.com/recipes/cuisine/german/'},
{'href': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'},
{'href': 'https://www.simplyrecipes.com/recipes/type/condiment/'},
{'href': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}]
{'href': 'https://www.simplyrecipes.com/',
'title': 'Simply Recipes Food and Cooking Blog', 'rel': ['home']},]
如您所见,大多数键是'href'
,大多数值包含'https://www.simplyrecipes.com/recipes/'
. 问题在于那些不符合此命名约定的键和值...
代码:
此代码遍历结构并使用re.findall
之间的字符串值'recipes/'
并继续/
为其对应的值创建一个新的键名。
for x in trash:
for y in x.values():
txt = ''
for i in re.findall("recipes/.*", y):
txt += i
title = txt.split('/')[1]
print({title: y})
输出:
如果我删除了不符合命名约定的keys
和包含代码的字符串值的命名约定,则可以正常工作,如下所示:values
'href'
'https://www.simplyrecipes.com/recipes/'
{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'}
{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/german/'}
{'season': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'}
{'type': 'https://www.simplyrecipes.com/recipes/type/condiment/'}
{'ingredient': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}
问题:代码的问题是,如果结构的键和值不符合代码中的命名约定
,我会得到一个。问题:我将如何改进此代码,以便它跳过任何未命名的键,如果它们被命名,如果它们的值不包含则将跳过?TypeError: expected string or bytes-like object
'href'
'href'
'https://www.simplyrecipes.com/recipes/'
解决方案
for d in trash:
for key, value in d.items():
if key != "href" or "https://www.simplyrecipes.com/recipes/" not in value:
continue # Move onto next iteration
txt = ''
for i in re.findall("recipes/.*", value):
txt += i
title = txt.split('/')[1]
print({title: value})
您可以使用 遍历字典的键和值dict.items()
。然后您可以使用if
语句来检查您的条件以及continue
是否不满足。
推荐阅读
- android - 函数在 Kotlin 中完成内部结果之前返回值
- c++ - 处理“未找到操作员”
- python - 如何立即从串行端口读取字节而不是等待换行符?
- css - ReactJs/Bootstrap:如何将 $enable-gradients 属性设置为 true?
- node.js - 如何摆脱 Node Mongo Express 应用程序中的 UnhandledPromiseRejectionWarning
- android - 已关闭的 Dismissible 小部件仍然是树的一部分。从列表中删除项目后重复出现此错误
- excel - 更改表格中特定单元格的字体颜色
- powershell - 使用 .exe 和 powershell 执行批处理脚本
- jestjs - 如何使用 Jest 在 Hapi 'onPreResponse' 回调函数中对逻辑进行单元测试?
- c++ - 有效计算多维数组的累积和?