![](/img/trans.png)
[英]How do I complete the 8.4.13 Owls, Part 2 problem in CodeHS Python?
[英]How do I use the enumerate function for CodeHS 8.4.13: Owls, Part 2?
這是我應該做的:
該計划是您之前的“貓頭鷹”計划的擴展。 你可以在這里找到你以前的程序!
除了只報告包含單詞 owl 的單詞數量之外,您還應該報告單詞出現的索引!
以下是您的程序運行示例:
Enter some text: Owls are so cool! I think snowy owls might be my favorite. Or maybe spotted owls.
有3個詞包含“貓頭鷹”。 它們出現在索引處:
[0, 7, 15]
正如您從輸出中看到的那樣,您必須使用另一個列表來存儲找到包含“owl”的單詞的索引。枚舉函數也可能派上用場!
這是我現在的代碼:
text = input("Enter some text: ")
text.lower()
text.split()
print "There are " + str(text.count("owl")) + " words that contained \"owl\"."
print "They occured at indices: for c, value in enumerate(text, 1):
print(c, value)
我完全不知道如何使用enumerate
函數。 我現在使用enumerate
函數的方式是我從其他網站獲得的。 當我嘗試運行此代碼時,我得到的第一件事是此錯誤:
Error: Line 5
ParseError: bad token on line 5
由此,我知道我使用enumerate
的方式是錯誤的。 但是,我不知道正確的使用方法。
在此行中:
print "They occured at indices: for c, value in enumerate(text, 1):
print(c, value)
你還沒有用"
結束字符串,所以 Python 繼續讀取越來越多,假設這個字符串還有更多,直到它到達你的文件的末尾。你不想要這個,作為部分: for c, value in enumerate(text, 1):
是你想讓 Python 執行的命令,它本身不是你想讓 Python 打印的字符串。所以首先我們關閉你的字符串:
print "They occured at indices: "
for c, value in enumerate(text, 1):
print(c, value)
這應該可以消除您的錯誤,但會打印錯誤的答案。 您還有另一個問題: text.split()
您不了解split()
工作原理。 我會把研究那部分留給你。
text = input("Enter some text: ")
text.lower()
text.split()
print "There are " + str(text.count("owl")) + " words that contained \"owl\"."
print "They occured at indices: for c, value in enumerate(text, 1):"
print "They occured at indices: "
for c, value in enumerate(text, 1):
print(c, value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.