假设我有一个字符串列表:
first item
second item
# first commented item
third item
# second commented item
如何从列表中删除第一个以#
开头的项目?
预期结果:
first item
second item
third item
# second commented item
假设我有一个字符串列表:
first item
second item
# first commented item
third item
# second commented item
如何从列表中删除第一个以#
开头的项目?
预期结果:
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
items[i].startswith('#')
。 - Idan K
for i, e in enumerate(items)
和items.pop(i)
会使其稍微更有效率。 - Sven Marnachfor e in items
是 1.2 秒,对于enumerate
是 1.7 秒。 - user225312#
开头的第一项接近末尾。这是唯一需要考虑性能的情况。 - Sven Marnach