【问题标题】:A Python program to print the longest consecutive chain of words of the same length from a sentence一个 Python 程序,用于打印句子中长度相同的最长连续单词链
【发布时间】: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

这是我不断遇到的问题,我只是不明白为什么索引超出范围。

对于解决此问题和修复程序的任何帮助,我将不胜感激。先感谢您。

【问题讨论】:

  • xwords中最后一项的索引时,你认为words[x+1]是什么?
  • 如果 x 已经增加了足够多的次数以至于它是列表中的最后一个索引,则 x+1 将超出范围。
  • 顺便说一句,你的循环从不使用 i 变量,这是你使用错误类型循环的线索......

标签: python string list for-loop


【解决方案1】:

使用groupby你可以得到结果

from itertools import groupby
string = "To be or not to be"
sol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))
print(sol)
# 'To, be, or'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2015-10-24
    • 2019-01-15
    • 2019-10-13
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多