Python 在列表理解中筛选和修改字符串
我有一个代码,它使用列表理解过滤字符串列表中的元素。像这样:Python 在列表理解中筛选和修改字符串,python,list-comprehension,Python,List Comprehension,我有一个代码,它使用列表理解过滤字符串列表中的元素。像这样: 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_
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:]
蟒蛇式的方法是什么?显然,我可以将其从理解改写为简单的循环,如:
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)]
我认为这样会更好:
def get_items(items):
return [
item[2:] if item.startswith('./') else 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')
]
使用嵌套列表:
def get_items():
return [item[2:] if item[:2] == './' else item for item in [your_list_comprehension] ]
您可以始终使用
map()
和filter()
方法来提高代码的可读性。
您可以在map和filter方法中找到示例
首先,您可以使用filter方法筛选列表中的项目。然后,您可以使用map函数进行所需的修改。投票人是否可以澄清原因?如果我不知道他们为什么认为答案不好,那么就不能完全改进答案。所以,按照其他两个答案所说的去做,但在所有项目上多做一个循环。这将对原始
列表中的项目进行全面扫描。\u理解(在外部项目开始之前进行评估),然后再次循环所有剩余的项,以可能删除开头的/
。将这两个操作分成两种不同的理解方式是没有好处的,时间复杂度会加倍,它不会保持不变。@GPhilo它看起来更整洁,可读性更强。而且,时间复杂度保持不变,仍然是O(N)。不,时间复杂度类是相同的,因为O表示法忽略了常数乘数。实际的时间复杂度是len(项目)+len(你的理解力)
,在最坏的情况下,这是一次性完成所有工作的两倍。另外,粘贴到原始列表中,您将看到这实际上并不整洁,也不可读。可读版本是@stasdeep'I’我很难理解您的逻辑,例如,如果您的物品不是“坏字符串”,您为什么要中断?或者“bad_string”是一个命名不当的填充词?我的bad,break应该是相反的。是的,我知道map和filter是这里最好的。但我不想对这段代码进行重大更改。