s = 'apple'
table = {}
for i in range(len(s)):
if s[i] in table:
table[s[i]] += 1
else:
table[s[i]] = 1
print(table)
# {'a': 1, 'p': 2, 'l': 1, 'e': 1}
算有一個字串中每個字元各有幾個:直接遍歷字元
s = 'apple'
table = {}
for char in s:
if char in table:
table[char] += 1
else:
table[char] = 1
print(table)
# {'a': 1, 'p': 2, 'l': 1, 'e': 1}
算有一個陣列每個每個字串各有幾個
words = ['apple', 'apple', 'orange', 'banana']
table = {}
for word in words:
if word in table:
table[word] += 1
else:
table[word] = 1
print(table)
# {'apple': 2, 'orange': 1, 'banana': 1}
算有一個陣列中每個每個數字出現幾次
numbers = [random.randint(0, 3) for _ in range(10)]
table = {}
for number in numbers:
if number in table:
table[number] += 1
else:
table[number] = 1
print(table)
# {0: 2, 2: 4, 1: 2, 3: 2}
上面的技巧其實只要注意到,如果當下的元素還沒有出現在 Table 裡面,我們要預設是 1 ,後面才可以繼續累加上去,不然會發生 Key not found 的情況。
到了這裡,如果已經熟練了 Hash Table ,有三個 API 可以在寫題目的時候,可以讓你寫的程式更少發生小細節寫錯的情況
API
功能
dict subclass for counting hashable objects
dict subclass that remembers the order entries were added
dict subclass that calls a factory function to supply missing values