首页 > 解决方案 > 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 的项目的长度,我能做些什么来解决这个问题?谢谢!

标签: pythonpython-3.x

解决方案


您不能同时迭代和修改列表,请尝试以下操作:

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)

推荐阅读