您好我正在尝试删除我预定义列表(前缀)中包含的所有令牌。下面是我的代码,并没有删除令牌。
prefixes = ('#', '@')
tokens = [u'order', u'online', u'today', u'ebay', u'store', u'#hamandcheesecroissant', u'#whoopwhoop', u'\u2026']
for token in tokens:
if token.startswith(prefixes):
tokens.remove(token)
答案 0 :(得分:3)
在迭代它时,从列表中删除项目并不真正有用。
您可以使用列表理解
tokens = [token for token in tokens if not token.startswith(prefixes)]
或者创建另一个列表,然后将要保留的项目添加到该列表中:
new_tokens = []
for token in tokens:
if not token.startswith(prefixes):
new_tokens.append(token)