python - 为什么我的 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)
解决方案
它不起作用,因为您在迭代列表时正在修改列表,这几乎总是一个坏主意。这将导致循环在您每次从中删除某些内容时跳过值。
在 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()
推荐阅读
- angular - 获取服务未在 Angular 6 中调用,即使在网络调用中也不会显示
- php - cakephp 3.8 中的多次插入
- c++ - 抛出异常:读取访问冲突。_Pnext 是 0xCDDC8C
- python - 如何在硒的小视口上拍摄高分辨率屏幕截图?
- categorical-data - 如何处理校准分类器中的分类变量?
- c - 在 c 中,我使用 graphics.h 开发游戏,但在游戏中出现颜色闪烁
- spring - Spring Boot 属性解析传入命令行参数
- android - 你怎么称呼这个键盘微调器(?),我如何用微调器替换它?
- centos - centos如何增加磁盘大小
- amazon-web-services - AWS CLI - S3 包括 AND 与 OR