我有此字符串列表和一些前缀。我想从列表中删除所有以这些前缀开头的所有字符串。我试过了:
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list:
list.remove(word.startswith(prexixes)
因此,我希望我的新列表为:
list = ['hi', 'holla']
但是我得到这个错误:
ValueError: list.remove(x): x not in list
怎么了
Greg的解决方案绝对是Pythonic,但是在您的原始代码中,您可能意味着这样的意思。观察到我们制作了一个副本(使用list[:]
语法)并遍历该副本,因为您不应在遍历列表时修改列表。
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list[:]:
if word.startswith(prefixes):
list.remove(word)
print list
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句