while循环表示returns每个字符出现的次数
While loop that returns the number of occurrences of each character
查看下面的 class 我需要编写代码来定义“字符频率”,因此它 returns 类似于下面的示例。
class EnhancedString:
def __init__(self, contents):
self._contents = str(contents)
def __str__(self):
return str(self._contents)
def __len__(self):
return len(self._contents)
def set_contents(self, contents):
self._contents = str(contents)
def get_contents(self):
return self._contents
**def character_frequency(self):**
"""
Returns a dictionary containing all characters found in _contents as keys, with integer values corresponding to the number of occurrences of each character. Use a while loop to traverse _contents.
:return: A dictionary with characters as keys and integers as values
Example use:
>>> c = EnhancedString("")
>>> print(c.character_frequency())
{}
>>> a = EnhancedString("abcdefg")
>>> print(a.character_frequency())
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1} >>> b = EnhancedString("aabcdefgaa")
>>> print(b.character_frequency())
{'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1} """
collections.Counter
将计算集合中的可哈希项目,在您的情况下,是字符串中的单个字符。
import collections
class EnhancedString:
def __init__(self, contents):
self._contents = str(contents)
def __str__(self):
return str(self._contents)
def __len__(self):
return len(self._contents)
def set_contents(self, contents):
self._contents = str(contents)
def get_contents(self):
return self._contents
def character_frequency(self):
return collections.Counter(self._contents)
s = EnhancedString("I am the very model of a modern major general")
print(s.character_frequency())
如果您想在没有任何额外模块的情况下执行此操作,您可以创建自己的字典并添加到其中。
def character_frequency(self):
counts = {}
for c in self._contents:
if c not in counts:
counts[c] = 1
else:
counts[c] += 1
return counts
或者使用异常块
def character_frequency(self):
counts = {}
for c in self._contents:
try:
counts[c] += 1
except KeyError:
counts[c] = 1
return counts
“while”循环更混乱。当您可以使用“for”进行迭代时,无需为集合建立索引。
def character_frequency(self):
counts = {}
i = 0
end = len(self._contents)
while i < end:
c = self._contents[i]
try:
counts[c] += 1
except KeyError:
counts[c] = 1
i += 1
return counts
这个工具不适合这项工作,但如果您需要使用 while 语句来完成它并且您希望您的代码有点 Pythonic,您可以使用迭代器:
content = "hello world"
counts = dict.fromkeys(content,0) # initialize all character counts to zero
iContent = iter(content) # iterator on characters
while True: # dummy loop, why not at this point ;)
try: counts[next(iContent)] += 1 # count characters
except StopIteration: break # stop when all characters counted
print(counts)
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
查看下面的 class 我需要编写代码来定义“字符频率”,因此它 returns 类似于下面的示例。
class EnhancedString:
def __init__(self, contents):
self._contents = str(contents)
def __str__(self):
return str(self._contents)
def __len__(self):
return len(self._contents)
def set_contents(self, contents):
self._contents = str(contents)
def get_contents(self):
return self._contents
**def character_frequency(self):**
"""
Returns a dictionary containing all characters found in _contents as keys, with integer values corresponding to the number of occurrences of each character. Use a while loop to traverse _contents.
:return: A dictionary with characters as keys and integers as values
Example use:
>>> c = EnhancedString("")
>>> print(c.character_frequency())
{}
>>> a = EnhancedString("abcdefg")
>>> print(a.character_frequency())
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1} >>> b = EnhancedString("aabcdefgaa")
>>> print(b.character_frequency())
{'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1} """
collections.Counter
将计算集合中的可哈希项目,在您的情况下,是字符串中的单个字符。
import collections
class EnhancedString:
def __init__(self, contents):
self._contents = str(contents)
def __str__(self):
return str(self._contents)
def __len__(self):
return len(self._contents)
def set_contents(self, contents):
self._contents = str(contents)
def get_contents(self):
return self._contents
def character_frequency(self):
return collections.Counter(self._contents)
s = EnhancedString("I am the very model of a modern major general")
print(s.character_frequency())
如果您想在没有任何额外模块的情况下执行此操作,您可以创建自己的字典并添加到其中。
def character_frequency(self):
counts = {}
for c in self._contents:
if c not in counts:
counts[c] = 1
else:
counts[c] += 1
return counts
或者使用异常块
def character_frequency(self):
counts = {}
for c in self._contents:
try:
counts[c] += 1
except KeyError:
counts[c] = 1
return counts
“while”循环更混乱。当您可以使用“for”进行迭代时,无需为集合建立索引。
def character_frequency(self):
counts = {}
i = 0
end = len(self._contents)
while i < end:
c = self._contents[i]
try:
counts[c] += 1
except KeyError:
counts[c] = 1
i += 1
return counts
这个工具不适合这项工作,但如果您需要使用 while 语句来完成它并且您希望您的代码有点 Pythonic,您可以使用迭代器:
content = "hello world"
counts = dict.fromkeys(content,0) # initialize all character counts to zero
iContent = iter(content) # iterator on characters
while True: # dummy loop, why not at this point ;)
try: counts[next(iContent)] += 1 # count characters
except StopIteration: break # stop when all characters counted
print(counts)
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}