例如,我試圖計算一個字母在我的輸入中出現的次數。另外,我正在嘗試使用我迄今為止學到的工具。到目前為止,我還沒有在我正在學習的課程中學習 .count 工具。
第一次我運行這段代碼:
any_word = input()
char_amount = {}
for i in any_word:
char_amount[i] = len(i)
print(char_amount)
我的輸入是:hello
結果是這樣的:我每次都在下面,并且我的 if 陳述句無法更新 to 的'l'
密鑰2
。
{'h': 1, 'e': 1, 'l': 1, 'o': 1}
我的 if 陳述句無法更新 to 的'l'
密鑰2
。我無法弄清楚要添加1
到'l'
鍵的 if 陳述句的邏輯,因為在每個鍵中都可以識別出重復項,結果如下。我假設我需要另一個變數,但我想不出邏輯。謝謝你的幫助:
{'h': 2, 'e': 2, 'l': 2, 'o': 2}
uj5u.com熱心網友回復:
你真的應該使用集合模塊中的 Counter 類:
from collections import Counter
value = input('Enter some text: ')
counter = Counter(value)
print(counter)
因此,對于“你好”的輸入,你會得到:
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Counter 子類 dict,因此您可以像訪問任何其他字典一樣訪問它
uj5u.com熱心網友回復:
使用char_amount[i] = char_amount.get(i, 0) 1
- 這將嘗試i
從 dict獲取密鑰char_amount
,如果未找到則回傳0
。然后將這個鍵的值增加1
any_word = input()
char_amount = {}
for i in any_word:
char_amount[i] = char_amount.get(i, 0) 1
print(char_amount)
印刷:
hello
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
uj5u.com熱心網友回復:
沒有收藏模塊:
word = input()
char_amount = {}
for char in word:
if char not in char_amount:
char_amount[char] = 1
else:
char_amount[char] = 1
print(char_amount)
使用集合模塊:
from collections import Counter
print(Counter(input()))
uj5u.com熱心網友回復:
使用內置計數器
from collections import Counter
my_counter = Counter("hello")
print(my_counter)
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504903.html