我试着在shell中创建一个简单的直方图,给出一个包含键的字典,这些键的值作为随机选择键的概率。我使用的格式由于某种原因不起作用。我也像往常一样使用str()函数进行显式转换,但仍然得到相同的错误。我使用了for循环,由于某种原因,当密钥的概率为1时,它就起作用了,但之后它给出了一个错误。你知道吗
这是调试窗口:
def histogram(word):
'takes a word and returns an histogram of it'
d = dict()
for letter in word:`enter code here`
d[letter] = d.get(letter,0) + 1
return (d)
>>> h = histogram('mississipi')
>>> print (h)
{'i': 4, 'p': 1, 's': 4, 'm': 1}
这部分工作得很好,但后来问题出现了
def histogram(word):
'takes a word and returns an histogram of it'
d = dict()
for letter in word:
d[letter] = '{}/{}'.format((d.get(letter,0) + 1),len(word))
return d
>>> print (histogram('mississippi'))
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print (histogram('mississippi'))
File "<pyshell#3>", line 5, in histogram
d[letter] = '{}/{}'.format((d.get(letter,0) + 1),len(word))
TypeError: Can't convert 'int' object to str implicitly
def histogram(word):
'takes a word and returns an histogram of it'
d = dict()
for letter in word:
d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word))
return d
>>> print (histogram('mississippi'))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print (histogram('mississippi'))
File "<pyshell#7>", line 5, in histogram
d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word))
TypeError: Can't convert 'int' object to str implicitly
在这之后,它似乎工作,但仍然显示错误
def histogram(word):
'takes a word and returns an histogram of it'
d = dict()
for letter in word:
d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word))
print (d)
>>> print (histogram('mississippi'))
{'m': '1/11'}
{'m': '1/11', 'i': '1/11'}
{'s': '1/11', 'm': '1/11', 'i': '1/11'}
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
print (histogram('mississippi'))
File "<pyshell#22>", line 5, in histogram
d[letter] = str(d.get(letter,0) + 1) + '/' + str(len(word))
TypeError: Can't convert 'int' object to str implicitly
您正在将字符串存储到字典中,然后尝试向字符串的值添加1。你知道吗
将计数和字符串格式分开;首先创建计数,然后用字符串生成最终字典:
您可能需要查看^{} 以替换您的字母计数循环:
相关问题 更多 >
编程相关推荐