简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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