python - Python3:为什么我的代码没有正确迭代?for/in 循环 + len(list[index])
问题描述
我正在尝试执行以下操作:
- 获取字符串输入,输入像一首诗,诗歌或说 将字符串拆分为单个单词的列表 确定列表的长度 循环
- 按索引号和每个列表索引的列表长度:
如果单词很短(3 个字母或更少),则将列表中的单词设为小写
如果单词很长(7 个字母或更多),则将列表中的单词设为大写
我的代码如下:
poem=input("Enter your poem here: ")
word_list=poem.split()
print(word_list)
length_list=len(word_list)
new_word=""
for index in range(0,length_list):
print(len(word_list[index]))
if len(word_list[index])<=3:
new_word=word_list.pop(index)
word_list.append(new_word.lower())
elif len(word_list[index])>=7:
print(word_list[index])
new_word=word_list.pop(index)
word_list.append(new_word.upper())
print(word_list)
当我运行它时,我得到以下信息:
Enter your poem here: Little fly, Thy summer’s play My thoughtless hand Has brushed away. Am not I A fly like thee? Or art not thou A man like me? # user input
['Little', 'fly,', 'Thy', 'summer’s', 'play', 'My', 'thoughtless', 'hand', 'Has', 'brushed', 'away.', 'Am', 'not', 'I', 'A', 'fly', 'like', 'thee?', 'Or', 'art', 'not', 'thou', 'A', 'man', 'like', 'me?']
6 #length first item on the list (Little)
4 #length second item on the list (fly)
3 #length third item on the list (Thy)
4 #length fifth item on the list (Play). Why is not calculating the index of the fourth item ("summer's) ??
2
4
3
5
2
1
3
5
2
3
1
4
3
2
2
3
3
3
2
3
2
2
['Little', 'fly,', 'summer’s', 'play', 'thoughtless', 'hand', 'brushed', 'away.', 'not', 'A', 'like', 'thee?', 'art', 'thou', 'man', 'like', 'thy', 'has', 'i', 'or', 'a', 'my', 'fly', 'me?', 'not', 'am']
如果想知道我的代码有什么问题,以至于循环不显示列表中大于 7 的项目的长度,我能做些什么来解决这个问题?谢谢!
解决方案
您不能同时迭代和修改列表,请尝试以下操作:
poem = input("Enter your poem here: ")
word_list = poem.split(" ")
print(word_list)
length_list = len(word_list)
new_word_list = []
for index in range(length_list):
if len(word_list[index]) <= 3:
new_word_list.append(word_list[index].lower())
elif len(word_list[index]) >= 7:
new_word_list.append(word_list[index].upper())
else:
new_word_list.append(word_list[index])
new_word_list = " ".join(new_word_list)
print(new_word_list)
推荐阅读
- java - 设置/更改默认 Java MaxHeapSize 或更改默认 JVM 命令设置
- python - 使用python对数据进行均匀和奇数切片
- azure - 是否可以在 Azure DevOps 的 Azure Powershell 任务中设置变量并将它们传递给另一个任务?
- java - 如何使用视图和路径变量测试 Spring 控制器?
- typescript - Vite 在 main.ts 中使用别名导入 CSS
- c++ - macOS 10.15 Catalina 上的英特尔编译问题:灾难性错误:无法打开源文件“stdlib.h”
- patroni - 如何从保护 postgresql 集群中删除节点?
- php - 如何在 WooCommerce 中将相关产品添加到订单电子邮件
- python - 为大量数据创建实例名称的最简单方法是什么
- java - 如何在 JFreeChart 上使用 createCombinedChart() 创建多个 ScatterPlot 图表?