我想要删除所有小于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)发布于 2019-07-13 09:48:01
它不起作用,因为您在迭代时修改了列表,这几乎总是一个坏主意。这将导致每次您从循环中删除某些内容时,循环将跳过值。
在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()
发布于 2019-07-13 10:07:50
简短而甜蜜:
word_list = list(filter(lambda x: len(x) > 3 and len(x) <= 7, word_list))使用filter方法,您可以将一个函数和一个序列作为参数,这将返回一个迭代器,只生成该函数返回True的序列中的项。在这个特定的例子中,因为您只需要长度严格大于3且不超过7的单词,所以可以定义一个lambda函数,该函数与filter方法一起完成这项工作。
https://stackoverflow.com/questions/57015532
复制相似问题