【问题标题】:While loop list index out of range - does not make sense?虽然循环列表索引超出范围 - 没有意义?
【发布时间】:2017-03-20 22:35:57
【问题描述】:
s = str(input("Please enter your line of text: ").lower())
only_vowels = re.sub(r"[^aeiou]", "", s)
c = (Counter(list(only_vowels)))  
print(c)

if len(c) >= 1:
    most = c.most_common()[-1]
    result = (most[0])

    i = -2
    if len(c)>=2:
        while (c.most_common()[i][1]) == most[1]:
            result = ", ".join((result, c.most_common()[i][0]))
            i = i-1


    print("The least common vowel(s) in the inserted sentence is/are",      (result),"and it/they appear(s)",most[1],"times.")

else:
    print("You have not inserted any vowels into this sentence.")

这段代码'while (c.most_common()[i][1]) == most[1]:'

有什么想法吗?

【问题讨论】:

  • cCounter,对吗?
  • 如果不了解 cmost 变量定义的更多上下文,以及在此 sn-p 之前如何使用它们等,将很难理解这个问题!
  • 请查看原始问题。我意识到问题是我的计数器功能出现故障。任何想法现在如何解决这个问题(原始 Q 编辑)
  • @LewisFirmin c 是一个 Counter 对象,并且正在打印。 c.most_common() 将返回键和值对的列表,然后您可以将其打印出来。
  • 谢谢。我很感激。现在已经更改了一些代码并编辑了问题......再次。我现在已经包含了整个编码。如果你有时间,请看一下。

标签: python list loops indexing while-loop


【解决方案1】:

列表中有多少条目? 如果 i = -2 那么你至少需要有 2 个条目,以便 Python 可以向后遍历列表。

【讨论】:

  • 嗨,Kev,请查看原始问题。我已经完全编辑了它。我意识到问题出在哪里,现在需要弄清楚如何解决我的计数器问题以使该编码能够正常工作!
【解决方案2】:

它打印“Counter”,因为 c 是 Counter 类型的对象。

Counter 有一种方法来获取最常见的事件,但它似乎没有一个用于最不常见的事件。这个怎么样:

from collections import defaultdict

occurrences = defaultdict(list)
vowels = "aeiou"

sentence = input()

for v in vowels:
    if v in sentence:
        occurrences[sentence.count(v)].append(v)

try:
    less_frequent_vowels = occurrences[min(occurrences)]
except ValueError:
    less_frequent_vowels = []

【讨论】:

  • 这看起来很有希望。它可以检索使用多少次元音。那么我将如何打印最少的出现次数?这可能不止一个元音! (如果e、i、o都只用了一次,我需要3个都打印出来)
  • 已经考虑到了。 less_frequent_vowels 是您要查找的内容的列表。
  • 尝试:print(", ".join(less_frequent_vowels))
猜你喜欢
  • 1970-01-01
  • 2018-10-15
  • 2016-10-03
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多