Python实现不使用endswith()移除列表中指定后缀结尾的元素
Python函数实现方案
实现逻辑
- 要直接修改原列表,选择倒序遍历列表索引,避免正序删除元素时出现索引错位漏判的问题
- 不调用
endswith()方法,手动逐字符比对单词末尾和指定后缀的每一位,判断是否匹配 - 先做边界判断:如果后缀长度为0,直接返回;如果单词本身长度小于后缀长度,直接跳过,不可能匹配
完整代码
def my_func(list_words, ending): end_length = len(ending) # 处理后缀为空的边界情况 if end_length == 0: return # 倒序遍历索引,删除元素不会影响未遍历的前置索引 for idx in range(len(list_words) - 1, -1, -1): current_word = list_words[idx] word_length = len(current_word) # 单词长度短于后缀,不可能匹配 if word_length < end_length: continue # 逐字符比对后缀 is_match = True for offset in range(end_length): if current_word[word_length - end_length + offset] != ending[offset]: is_match = False break if is_match: del list_words[idx]
测试验证
list_words = ["hello", "jello","whatsup","right", "cello", "estello"] ending = "ello" my_func(list_words, ending) print(list_words)
运行后输出:
['whatsup', 'right']
内容的提问来源于stack exchange,提问作者yowhatsup123
相关产品推荐
相关产品推荐

