gpt4 book ai didi

python - 从列表中删除与子字符串匹配的项目

转载 作者:IT老高 更新时间:2023-10-28 20:57:16 30 4
gpt4 key购买 nike

如果一个元素与子字符串匹配,如何从列表中删除它?

我尝试使用 pop()enumerate 方法从列表中删除一个元素,但似乎我缺少一些需要删除的连续项目:

sents = ['@$\tthis sentences needs to be removed', 'this doesnt',
'@$\tthis sentences also needs to be removed',
'@$\tthis sentences must be removed', 'this shouldnt',
'# this needs to be removed', 'this isnt',
'# this must', 'this musnt']

for i, j in enumerate(sents):
if j[0:3] == "@$\t":
sents.pop(i)
continue
if j[0] == "#":
sents.pop(i)

for i in sents:
print i

输出:

this doesnt
@$ this sentences must be removed
this shouldnt
this isnt
#this should
this musnt

期望的输出:

this doesnt
this shouldnt
this isnt
this musnt

最佳答案

像这样简单的东西怎么样:

>>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
['this doesnt', 'this shouldnt', 'this isnt', 'this musnt']

关于python - 从列表中删除与子字符串匹配的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12666897/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com