簡體   English   中英

dict.setdefault() 如何計算字符數?

[英]How does dict.setdefault() count the number of characters?

我從《用 Python 自動化無聊的東西》一書中得到了這段代碼,我不明白setdefault()方法如何計算唯一字符的數量。

代碼:

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1
print(count)

根據這本書, setdefault()方法在字典中搜索鍵,如果未找到則更新字典,如果找到則不執行任何操作。 但我不明白setdefault的計數行為以及它是如何完成的?

輸出:

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
 'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}

請向我解釋這一點。

在您的示例中 setdefault() 相當於此代碼...

if character not in count:
    count[character] = 0

這是(可以說)做同樣事情的更好方法:

from collections import defaultdict
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = defaultdict(int)
for character in message:
    count[character] = count[character] + 1
print(count)

它有效,因為默認 int 為 0。

一個更好的方法如下:

from collections import Counter
print(Counter(
    'It was a bright cold day in April, '
     'and the clocks were striking thirteen.'))

至少在這種情況下最好使用 defaultdict 。

from collections import defaultdict
count = defaultdict(int)
for character in message:
  count[character] += 1

defaultdict 是用無參數函數構造的,它創建了一個任何默認值應該是的實例。 如果鍵不存在,則此函數為其提供一個值並為您在字典中插入鍵值。 由於 int() 返回 0,因此在這種情況下它被正確初始化。 如果您希望它初始化為某個其他值 n,那么您可以執行類似的操作

count = defaultdict(lambda : n)

我正在使用相同的教科書,但遇到了同樣的問題。 提供的答案比所討論的示例更復雜,因此它們實際上並沒有解決問題:上面的問題是 - 代碼如何理解它應該計算出現次數。 事實證明,它並沒有真正“計數”。 它只是不斷地改變這些值,直到它停止。 因此,經過漫長而痛苦的研究,我是這樣向自己解釋的:

message='It was a bright,\
cold day in April,\
and the clocks were \
striking thirteen.'
count={}   # "count" is set as an empty dictionary, which we want to fill out
for character in message:  # for each character, do the following:
    count.setdefault(character,0)  # if the character is not there,
                                   # take it from the message above
                                   # and set it in the dictionary
                                   # so the new key is a letter (e.g. 'a') and value is 0
                                   # (zero is the only value that we can set by default
                                   # otherwise we would gladly set it to 1 (to start with the 1st occurrence))
                               # but if the character already exists - this line will do nothing! (this is pointed out in the same book, page 110) 
                               # the next time it finds the same character
                               # - which means, its second occurrence -
                               # it won't change the key (letter)
                               # But we still want to change the value, so we write the following line:
    count[character]=count[character]+1  # and this line will change the value e.g. increase it by 1
                                         # because "count[character]",
                                         # is a number,  e.g. count['a'] is 1 after its first occurrence
                                         # This is not an "n=n+1" line that we remember from while loops
                                         # it doesn't mean "increase the number by 1
                                         # and do the same operation from the start"
                                         # it simply changes the value (which is an integer) ,
                                         # which we are currently processing in our dictionary, by 1
                                # to summarize: we want the code to go through the characters
                                # and only react to the first occurence of each of them; so
                                # the setdefault does exactly that; it ignores the values;
                                # second, we want the code to increase the value by 1
                                # each time it encounters the same key; 
                                # So in short:
                                # setdefault deals with the key only if it is new (first occurence)
                                 # and the value can be set to change at each occurence,
                                 # by a simple statement with a "+" operator
                                 # the most important thing to understand here is that
                                 # setdefault ignores the values, so to speak,
                                 # and only takes keys, and even them only if they are newly introduced.
print(count)   # prints the whole obtained dictionary

@egon 的回答非常好,它回答了這里提出的疑問。 我只是稍微修改了代碼,希望它現在很容易理解。

message = 'naga'
count = {}
for character in message:
    count.setdefault(character,0)
    print(count)
    count[character] = count[character] + 1
    print(count)  
print(count)

   and the output will be as follows 

  {'n': 0} # first key and value set in count 
  {'n': 1} # set to this value when count[character] = count[character] + 1 is executed.
  {'n': 1, 'a': 0} # so on 
  {'n': 1, 'a': 1}
  {'g': 0, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 2}
  {'g': 1, 'n': 1, 'a': 2}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This is an empty dictionary. We will add key-value pairs to this dictionary with the help of the following lines of code (The for-loop and its code block).

for character in message: #The loop will run for the number of single characters (Each letter & each space between the words are characters) in the string assigned to 'message'.
                          #That means the loop will run for 73 times.
                          #In each iteration of the loop, 'character' will be set to the current character of the string for the running iteration.
                          #That means the loop will start with 'I' and end with '.'(period). 'I' is the current character of the first iteration and '.' is the current character of the last iteration of the for-loop.

    count.setdefault(character, 0) #If the character assigned to 'character' is not in the 'count' dictionary, then the character will be added to the dictionary as a key with its value being set to 0.
    count[character] = count[character] + 1 #The value of the key (character added as key) of 'count' in the running iteration of the loop is incremented by one.
                                            #As a result of a key's value being incremented, we can track how many times a particular character in the string was iterated.
                                            #^It's because the existing value of the existing key will be incremented by 1 for the number of times the particular character is iterated.
                                            #The accuracy of exactly how many times a value should be incremented is ensured because already existing keys in the dictionary aren't updated with new values by set.default(), as it does so only if the key is missing in the dictionary. 

print(count) #Prints out the dictionary with all the key-value pairs added.
             #The key and its value in each key-value pair represent a specific character from the string assigned to 'message' and the number of times it's found in the string, respectively.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM