0
def count_chars(s):
    '''Return a dict that contains each character in str s as a key. The
    value associated with each key is the number of times that character
    occurs in s.'''

    d = {}
    for ch in s:
       if ch in d:
          d[ch] += 1
       else:
          d[ch] = 1
    return d

我没有得到代码中的第三行“if ch in d”。如果字典中还没有任何条目,为什么该字符会出现在字典中?

另外,我不明白 d[ch] += 1 应该是什么意思,以及为什么会有 else 语句。有人可以帮帮我吗?

4

4 回答 4

2

理解这样的代码最简单的方法是添加prints 以查看它实际在做什么。所以,

def count_chars(s):
    '''Return a dict that contains each character in str s as a key. The
    value associated with each key is the number of times that character
    occurs in s.'''

    d = {}
    for ch in s:
       if ch in d:
          print('{} is in d'.format(ch))
          d[ch] += 1
       else:
          print('{} is NOT in d'.format(ch))
          d[ch] = 1
      print('d is now: {}'.format(d))
    return d

count_chars('abcdaaaa')

告诉你:

a is NOT in d
d is now: {'a': 1}
b is NOT in d
d is now: {'a': 1, 'b': 1}
c is NOT in d
d is now: {'a': 1, 'c': 1, 'b': 1}
d is NOT in d
d is now: {'a': 1, 'c': 1, 'b': 1, 'd': 1}
a is in d
d is now: {'a': 2, 'c': 1, 'b': 1, 'd': 1}
a is in d
d is now: {'a': 3, 'c': 1, 'b': 1, 'd': 1}
a is in d
d is now: {'a': 4, 'c': 1, 'b': 1, 'd': 1}
{'a': 4, 'c': 1, 'b': 1, 'd': 1}
于 2012-04-23T02:29:17.493 回答
1

与许多其他脚本语言不同,Python 不会自动创建元素。在文档中,您将看到 getdefault() 和 setdefault() 方法,这对于此类情况很有用。您还可以按照此线程中的说明对 dict 进行子类化。

于 2012-04-23T02:19:40.840 回答
1

因为每次执行循环时,您要么在字典中添加或更新键。如果密钥已存在,则您正在更新其值。

于 2012-04-23T02:16:32.860 回答
1

我没有得到代码中的第三行“if ch in d”。

它的意思正是它所说的:它检查是否chd.

如果字典中还没有任何条目,为什么该字符会出现在字典中?

因为它可能,最终。代码在for循环内,循环的目的是安排代码运行多次。其中一些运行将内容放入字典中。

另外,我不明白 d[ch] += 1 应该是什么意思

它意味着语言参考所说的意思。

以及为什么会有 else 语句。

因为当条件不成立时我们想做一些事情,当它成立时我们也想做一些事情。

于 2012-04-23T03:04:08.197 回答