【发布时间】:2022-12-04 03:09:15
【问题描述】:
我的任务是编写一个 Python 脚本,该脚本将从一个句子中输出相同长度的最长连续单词链。例如,如果输入是“To be or not to be”,输出应该是“To, be, or”。
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)
为了将输入的字符串转换为单词列表并去掉任何标点符号,我使用了 replace() 和 split() 方法。该列表的第一个单词将被附加到一个名为“same”的新列表中,该列表将包含具有相同长度的单词。然后,for 循环将逐个比较单词的长度,如果它们的长度匹配,则将它们附加到此列表中,如果不匹配,则清除列表。
if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range
这是我不断遇到的问题,我只是不明白为什么索引超出范围。
对于解决此问题和修复程序的任何帮助,我将不胜感激。先感谢您。
【问题讨论】:
-
当
x是words中最后一项的索引时,你认为words[x+1]是什么? -
如果
x已经增加了足够多的次数以至于它是列表中的最后一个索引,则x+1将超出范围。 -
顺便说一句,你的循环从不使用
i变量,这是你使用错误类型循环的线索......
标签: python string list for-loop