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

慕的地10843
TA贡献1785条经验 获得超8个赞
# To support matches from the beginning, not any matches:
items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'
filter(lambda x: x.startswith(prefix), items)

收到一只叮咚
TA贡献1821条经验 获得超4个赞
在交互式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)
添加回答
举报
0/150
提交
取消