2011-02-13 68 views
4

假設我有一個字符串列表:刪除從列表匹配準則第一次出現

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

如何刪除與#從列表開始的第一個項目?

預期的結果:

first item 
second item 
third item 
# second commented item 

回答

6
>>> items = ["First", "Second", "# First", "Third", "# Second"] 
>>> for e in items: 
...  if e.startswith('#'): 
...    items.remove(e) 
...    break 
... 
>>> items 
['First', 'Second', 'Third', '# Second'] 
1
items = ["First", "Second", "# First", "Third", "# Second"] 
for i in xrange(len(items)): 
    if items[i][0] == '#': 
     items.pop(i) 
     break 
print items 
+0

如果有列表中的空字符串這將失敗。 – 2011-02-13 18:36:05

+1

只需使用`items [i] .startswith('#')`代替。 – 2011-02-13 18:42:23

相關問題