简体   繁体   English

从列表中删除与条件匹配的第一个匹配项

[英]Remove first occurrence that matches criteria from a list

Suppose I have a list of strings: 假设我有一个字符串列表:

first item
second item
# first commented item
third item
# second commented item

How do I remove the first item that starts with # from the list? 如何从列表中删除以#开头的第一个项目?

Expected result: 预期结果:

first item
second item
third item
# second commented item
>>> items = ["First", "Second", "# First", "Third", "# Second"]
>>> for e in items:
...     if e.startswith('#'):
...             items.remove(e)
...             break
... 
>>> items
['First', 'Second', 'Third', '# Second']
items = ["First", "Second", "# First", "Third", "# Second"]
for i in xrange(len(items)):
    if items[i][0] == '#':
        items.pop(i)
        break
print items

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM