【发布时间】:2016-02-13 09:24:01
【问题描述】:
我正在尝试在 python 中编写一个字数统计程序。为此,我使用字典来存储单词的数量。
字典的格式为 d[int] = [单词数组]。
添加单词时,如果单词已经存在于 dict 中,则删除该单词并附加到下一个键。
在执行 d[index].append(word) 时,它以某种方式被添加为新键。难道我做错了什么?我在 Ubuntu 上使用 python 3.4.3 和 2.7.9。
def count_words(s, n):
d = {}
d[1] = []
word_array = []
for word in s.split():
if word not in word_array:
d[1].append(word)
word_array.append(word)
else:
keys = list(d.keys())
for key in keys:
if word in d[key]:
index = key+1
d[key].remove(word)
if index in d.keys():
print ('appending %s at %d on %s' % (word, index, d[index]))
d[index].append(word)
#print d[index]
else:
d[index] = list([word])
print ('%s -> %s' % (word, d))
print (d)
def test_run():
"""Test count_words() with some inputs."""
count_words("cat bat mat cat bat cat", 3)
#print count_words("betty bought a bit of butter but the butter was bitter", 3)
#print count_words('london bridge is falling down falling down falling down london bridge is falling down my fair lady', 5)
if __name__ == '__main__':
test_run()
【问题讨论】:
-
顺便说一句,4 个空格缩进会使代码更具可读性;
index in d.keys()->index in d,list([word])->[word] -
你可以看看
Counters。 -
有更好的方法来解决这个问题。但是,这只是我为检查某些内容而创建的一次性代码。我的问题是这是一个错误还是编程问题?
标签: python python-2.7 python-3.x