我有以下練習:
文本在一行中給出。對于文本中的每個單詞,計算它在它之前出現的次數。為簡單起見,我們假設輸入中沒有數字、標點或特殊符號。連續的單詞之間用一個或多個空格隔開。
該練習明確要求使用字典。
輸入:
the block on the block on the block on the floor
輸出:
0 0 0 1 1 1 2 2 2 3 0
到目前為止的代碼:
my_words={}
s = input()
nums_str = s.split()
count=0
for x in nums_str:
my_words.update({count:0})
count= count 1
the block on the block on the block on the floor
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0}
這將列印出一個字典,其中每個單詞的索引為一個數字,一個零。
這個想法是用它來記錄每個單詞在它之前的位置。
這就是我不明白如何記錄每個單詞在其自身之前的位置。
uj5u.com熱心網友回復:
為了實作這一點,您需要在每次迭代后獲取 counter 的值。此外,為了使此代碼可在任何地方重用,您可以使用它創建一個函式,如下所示:
def dynamic_counter(sequence, delimiter=' '):
word_dict, count_list = {}, []
for word in sequence.split(delimiter):
count_list.append(word_dict.get(word, 0))
word_dict[word] = word_dict.get(word, 0) 1
return count_list
sentence = "the block on the block on the block on the floor"
print(*dynamic_counter(sentence))
uj5u.com熱心網友回復:
僅靠字典是行不通的。如果你添加一個串列,你可以在那里收集當前的字數。
這個想法是檢查單詞是否在字典中。如果沒有,則添加它并將值設定為0. 如果存在,則將值增加1。然后使用當前添加或更新的值。
s = 'the block on the block on the block on the floor'
words = {}
counts = []
for word in s.split():
if word not in words:
words[word] = 0
else:
words[word] = 1
counts.append(words[word])
print(counts)
結果: [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 0]
如果您不需要為進一步的任務收集輸出,您可以洗掉串列并只列印當前值。
s = 'the block on the block on the block on the floor'
words = {}
for word in s.split():
if word not in words:
words[word] = 0
else:
words[word] = 1
print(words[word], end=' ')
使用字典get方法和默認值的相同方法。(您可以在 mousetail 的回答中看到類似的方法)
words = {}
for word in s.split():
words[word] = words.get(word, -1) 1
print(words[word], end=' ')
uj5u.com熱心網友回復:
用簡單的字典解決:
words = input().split()
count = {}
for word in words:
print(count.get(word, 0), end=" ") # print earlier words
count[word]=count.get(word, 0) 1 # increase the counter
uj5u.com熱心網友回復:
不清楚為什么必須使用字典。沒有字典的幫助,你可以這樣做:
mystring = 'the block on the block on the block on the floor'
mywords = mystring.split()
outlist = [mywords[:i].count(w) for i, w in enumerate(mywords)]
print(outlist)
如果您需要問題中顯示的格式的字典,則:
mystring = 'the block on the block on the block on the floor'
mywords = mystring.split()
mydict = {k: v for k, v in enumerate([mywords[:i].count(w) for i, w in enumerate(mywords)])}
print(mydict)
uj5u.com熱心網友回復:
代碼非常簡單。練習是關于學習字典的,所以建議使用它。
words = input().split()
d = {}
for word in words:
if word in d:
d[word] =1
else:
d[word] = 0
print(d[word], end = " ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334485.html
上一篇:如何確定從txt檔案中讀取專案的頻率并列印專案名稱以及專案出現的次數?
下一篇:用用戶輸入填充字典時的重復回應
