2020年4月2日 星期四

Python3 - How to count items in list?

[Method 1] Count item in list.
# Sample list
sl=[1,2,3,1,2,3,4,5,8]  

# Count item 2
sl.count(2)
→ return 2

[Method 2] Count all item in list.
# Import defaultdict
from collections import defaultdict

# Sample list
sl=[1,2,3,1,2,3,4,5,8]   

# Create hash table
ht=defaultdict(int)

# Hash Table Status
defaultdict(<class 'int'>, {})

# Create hash table & count {items: <count>}
for x in sl:
    ht[x]+=1

# Hash Table Status
defaultdict(<class 'int'>, {1: 2, 2: 2, 3: 2, 4: 1, 5: 1, 8: 1})

# How many "2" in list?
ht[2]
→ return 2