根据内容过滤字符串列表

给定list ['a','ab','abc','bac'],我想计算一个包含字符串的列表'ab'。即结果是['ab','abc']。如何在Python中完成?



慕雪6442864
浏览 289回答 3
3回答

慕的地10843

# To support matches from the beginning, not any matches:items = ['a', 'ab', 'abc', 'bac']prefix = 'ab'filter(lambda x: x.startswith(prefix), items)

收到一只叮咚

在交互式shell中快速尝试了一下:>>> l = ['a', 'ab', 'abc', 'bac']>>> [x for x in l if 'ab' in x]['ab', 'abc']>>>为什么这样做?因为为字符串定义了in运算符,以表示:“是”的子字符串。另外,您可能需要考虑写出循环,而不是使用上面使用的列表理解语法:l = ['a', 'ab', 'abc', 'bac']result = []for s in l:   if 'ab' in s:       result.append(s)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python