这段代码是从以字母表中指定字母开头的列表中删除单词。麻烦的是,它只删除了一些条目。 当我运行它来删除以' a'开头的单词时,只有' ana',' agra'' aba'被删除。为什么?也可以重写条件以包括一系列字母,例如a-i?
def delete_from_list():
discarded=[]
#list_of_terms = pickle.load( open( "list_it.txt", "rb" ) )
list_of_terms = ['ana', 'agro','agra',' aaa','aba','bab','Banana', 'band', 'bink' ]
print('start length = ', len(list_of_terms))
for item in list_of_terms:
item.lower().strip()
if item.startswith('a'):
discarded.append(item)
list_of_terms.remove(item)
print('end_length = ', len(list_of_terms))
print(discarded, list_of_terms)
感谢您的时间和帮助。
答案 0 :(得分:2)
就像DeepSpace和帕特里克所说的那样,你在从列表中删除项目的同时重复遍历列表。要查找从a-i开始的单词,您可以尝试使用正则表达式。
regex=re.compile('^[a-i]')
if re.match(regex, somestring):
# do things
插入符号匹配字符串的开头,方括号内的a-i表示所需的字符集。有关详细信息,请参阅python docs on regex。