Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我正在尝试运行一个程序,该程序将根据原始输入告诉您一个字母在字符串中重复了多少次_Python_Python 2.7_Raw Input - Fatal编程技术网

Python 我正在尝试运行一个程序,该程序将根据原始输入告诉您一个字母在字符串中重复了多少次

Python 我正在尝试运行一个程序,该程序将根据原始输入告诉您一个字母在字符串中重复了多少次,python,python-2.7,raw-input,Python,Python 2.7,Raw Input,我的错误: dict = {} raw_input('Please enter a string :') letter = raw_input() for letter in raw_input: if letter not in dict.keys(): dict[letter] = 1 else: dict[letter] += 1 print dict 第9行,在 TypeError:“内置函数”或“方法”对象不可编辑 您收到此错误是因为

我的错误:

dict = {}
raw_input('Please enter a string :')
letter = raw_input()
for letter in raw_input:
    if letter not in dict.keys():
        dict[letter] = 1
    else:
        dict[letter] += 1

print dict
第9行,在
TypeError:“内置函数”或“方法”对象不可编辑

您收到此错误是因为您试图对原始输入中的字母进行迭代。:

但是,在Python中,只有具有
\uuuuu iter\uuuuu()
方法的对象才是可iterable的,而
原始输入
没有此方法(它也是Python中的内置方法)。您可以使用
type()
查找对象的类型,并使用
dir()
查找对象的方法列表:


当我将原始输入中的字母
更改为原始输入中的字母
,输入为“问题”,输出为“{e':1,'i':1,'o':1,'n':1,'q':1,'s':1,'u':1,'t':1}”,并且我认为可以将for循环中的部分代码更改为
dict[letter]=dict.get(letter,0)+1
如果您愿意。

到目前为止,最简单的方法是使用内置的
集合
模块中的
计数器
类:

dic = {}
letters = raw_input('Please enter a string :')
for letter in letters:
    if letter not in dic.keys():
        dic[letter] = 1
    else:
        dic[letter] += 1

print dic

# output:
# Please enter a string :success
# {'e': 1, 's': 3, 'c': 2, 'u': 1}
计数器
可以像字典一样访问:

from collections import Counter

print Counter(raw_input('Please enter a string: '))

与你的问题并不相关,但请查阅defaultdict。这对此类代码很有帮助。您问题的答案已在下面处理。您想要迭代原始输入()的结果,这不是您所做的。这个问题肯定表明作者自己所做的研究很少。在实际发布类似问题之前,请多展示一点您自己的努力,而不仅仅是复制您收到的第一条错误消息。(或者至少把你的错误信息复制到谷歌上,10次中有8次是有帮助的)
dic = {}
letters = raw_input('Please enter a string :')
for letter in letters:
    if letter not in dic.keys():
        dic[letter] = 1
    else:
        dic[letter] += 1

print dic

# output:
# Please enter a string :success
# {'e': 1, 's': 3, 'c': 2, 'u': 1}
from collections import Counter

print Counter(raw_input('Please enter a string: '))
>>> a = Counter('spam spam spam')
>>> print a
Counter({'a': 3, 'p': 3, 's': 3, 'm': 3, ' ': 2})
>>> print a['s']
3