编程语言
首页 > 编程语言> > python-删除以特定字符开头的令牌

python-删除以特定字符开头的令牌

作者:互联网

嗨,我正在尝试删除预定义列表(前缀)中包含的所有那些标记.以下是我的代码,并且没有删除令牌.

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)

解决方法:

在迭代列表时从列表中删除项目实际上并不起作用.

您可以使用列表理解

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)

标签:tokenize,string,python
来源: https://codeday.me/bug/20191111/2022305.html