首页 > 解决方案 > 过滤和修改列表理解中的字符串

问题描述

我有一个代码,它使用列表理解过滤字符串列表中的元素。像这样:

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)

但它看起来真的很丑。还有更优雅的吗?

标签: pythonlist-comprehension

解决方案


你可以把它塞进理解中:

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)]

推荐阅读