TypeError:即使尝试转换和格式化,也无法将“int”对象隐式转换为str

2024-04-20 04:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在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 

Tags: inforgetlendeflinewordfile
1条回答
网友
1楼 · 发布于 2024-04-20 04:49:16

您正在将字符串存储到字典中,然后尝试向字符串的值添加1。你知道吗

将计数和字符串格式分开;首先创建计数,然后用字符串生成最终字典:

def histogram(word):
    d = {}
    # create counts
    for letter in word:
        d[letter] = d.get(letter, 0) + 1
    # produce a dictionary with count/len strings
    return {l: '{}/{}'.format(c, len(word)) for l, c in d.items()}

您可能需要查看^{}以替换您的字母计数循环:

from collections import Counter

def histogram(word):
    d = Counter(word)
    return {l: '{}/{}'.format(c, len(word)) for l, c in d.items()}

相关问题 更多 >