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

时间:2011-02-13 18:23:17

标签: python

假设我有一个字符串列表:

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

如何从列表中删除以#开头的第一个项目?

预期结果:

first item
second item
third item
# second commented item

2 个答案:

答案 0 :(得分:7)

>>> items = ["First", "Second", "# First", "Third", "# Second"]
>>> for e in items:
...     if e.startswith('#'):
...             items.remove(e)
...             break
... 
>>> items
['First', 'Second', 'Third', '# Second']

答案 1 :(得分:1)

items = ["First", "Second", "# First", "Third", "# Second"]
for i in xrange(len(items)):
    if items[i][0] == '#':
        items.pop(i)
        break
print items