python - 过滤和修改列表理解中的字符串
问题描述
我有一个代码,它使用列表理解过滤字符串列表中的元素。像这样:
def get_items(items):
return [item for item in items if not item.startswidth('some_prefix') and not (item == 'bad_string' or item.endswith('bad_postfix') of 'bad_substr' in item) and not ites.endswidth('another_bad_postfix')]
现在我不仅要过滤,还要修改项目,并为每个项目应用这个逻辑:
if item.startswith('./'):
item = item[2:]
这样做的pythonic方法是什么?显然,我可以将其从理解中重写为简单的循环,例如:
for item in items:
res = []
if not item.startswidth('some_prefix') and not (item == 'bad_string' or item.endswith('bad_postfix') of 'bad_substr' in item) and not ites.endswidth('another_bad_postfix'):
break
if item.startswith('./'):
item = item[2:]
res.append(item)
但它看起来真的很丑。还有更优雅的吗?
解决方案
你可以把它塞进理解中:
return [item[2:] if item.startswith('./') else item for item in ...
但是请注意,以这种方式编写的理解有点难以理解。您可以在单独的函数中分离出项目标准:
def item_is_good(item):
return( not item.startswidth('some_prefix') and
not (item == 'bad_string' or
item.endswith('bad_postfix') of
'bad_substr' in item) and
not item.endswidth('another_bad_postfix') )
将理解转化为
[item[2:] if item.startswith('./') else item for item in items if item_is_good(item)]
推荐阅读
- html - 如何在角度 7 中将值从一页传递到另一页
- sql - Oracle sql从带有限制的子句插入多个表
- shell - 从 ifconfig 中提取 IP 地址和接口名称
- elasticsearch - Elastic Search 高级客户端 - 如何使用发布请求进行搜索?
- json - 为什么字符串/json 在 post 请求中发送到 .netcore web api 导致 null?
- c - C:宏不能正确转换为 int
- regex - 如何匹配 OR 语句中最后出现的字符集?
- c# - 如何使用 C# 调用 Fortran DLL 函数
- angular - 如何计算Angular中数组的概率?
- python - 使用 PySCIPOpt 限制求解时间(Python 的 SCIP ILP 优化)