首页 > 解决方案 > 为什么我的 small_words() 和 large_words() 函数不起作用

问题描述

我想消除所有短于 3 个字符和长于 7 个字符的单词,但我的功能似乎不起作用

import random
import sys

word_list = ['zebra',  'memory', 'desktop', 'earthquake', 
'infinity','marker', 'chocolate', 'school', 'microwave', 
'microphone', 'battle','battery', 'gorilla', 'memory', 'calendar', 
'plant', 'pants', 'trophy','pollution', 'carpenter', 'son', 'join']

guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []

def main():
    small_words()
    large_words()

def small_words():
    global word_list
    for word in word_list:
        if len(word) <= 3:
            word_list.remove(word)

def large_words():
    global word_list
    for words in word_list:
        if len(words) > 7:
            word_list.remove(words)

标签: pythonpython-3.x

解决方案


它不起作用,因为您在迭代列表时正在修改列表,这几乎总是一个坏主意。这将导致循环在您每次从中删除某些内容时跳过值。

在 python 中执行此操作的方法是使用列表推导。它足够短,你真的不需要函数:

word_list = [word for word in word_list if len(word) > 3 ]
word_list = [word for word in word_list if len(word) <= 7]

或合二为一:

word_list = [word for word in word_list if 3 < len(word) <= 7]

另一种方法是使用filter()


推荐阅读