为什么我的small_words()和large_words()函数不起作用

时间:2019-07-13 01:41:23

标签: python python-3.x

我想消除所有少于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)

2 个答案:

答案 0 :(得分:1)

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

在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()

答案 1 :(得分:1)

又甜又甜:

word_list = list(filter(lambda x: len(x) > 3 and len(x) <= 7, word_list))

使用filter方法,您可以将一个函数和一个序列作为参数,返回一个可迭代的对象,只产生该函数返回True的序列中的项。在这种特定情况下,由于您只希望长度严格大于3且不大于7的单词,因此可以定义一个lambda函数,该函数与filter方法一起完成此工作。