我有以下练习:
文本在单行中给出。对于文本中的每个单词,计算其在其前面出现的次数。为简单起见,我们假设输入中没有数字、标点符号或特殊符号。连续的单词之间用一个或多个空格分隔。
练习明确要求使用字典。
输入:
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}
输出一个字典,每个单词的索引是一个数字和一个零。
这个想法是用它来记录每个单词在它自己之前的位置。
这就是我不懂的地方如何记录每个单词在自己前面的位置
单靠字典是不够的。如果你添加一个列表,你可以在那里收集当前字数。
目的是检查单词是否在字典中。如果没有,则将其添加并设置为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)
Result:[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=' ')
为了实现这一点,您需要在每次迭代后获取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))
用简单的字典解决方案:
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
不清楚为什么你有用字典。没有字典的帮助,您可以这样做:
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)
代码非常简单。这个练习是关于学习字典的,所以建议使用它。
words = input().split()
d = {}
for word in words:
if word in d:
d[word]+=1
else:
d[word] = 0
print(d[word], end = " ")