0%

[學習] Python List

常遇到的問題

  • find the duplicate elements in the list
  • count the duplicate elements in the list
  • remove the duplicate elements in the list

List.count() 用法

計算指定的值在 list 出現幾次

語法:list.count(element)

input:

1
2
3
my_list = [2, 3, 1, 4, 2, 5, 3, 7]
print(my_list.count(3))
print(my_list.count(7))

output:

1
2
2
1

進階

將 list 裡面所有的 element 都記錄下有幾個

input:

1
2
3
4
dup_list = ["a", "c", "a", "c", "b", "a"]
clear_dict = {i: dup_list.count(i) for i in dup_list}

print(clear_dict)

output:

1
{'a': 3, 'c': 2, 'b': 1}

另一種用法 Counter

需要先 import
語法:
from collections import Counter
Counter(List/String)

counter 出來的型態通常會轉成 Dictionary 會比較方便~
在下面也會示範有轉成 dict 跟沒轉成 dict 的差別

input:

1
2
3
4
5
6
7
from collections import Counter
dup_list = ["a", "c", "a", "c", "b", "a"]
count_list = dict(Counter(dup_list))
count_string = Counter('acacaba')

print(count_list)
print(count_string)

output:

1
2
{'a': 3, 'c': 2, 'b': 1}
Counter({'a': 4, 'b': 1, 'c': 2})

Counter 的額外用法

找出出現次數前 n 多

語法: Counter.most_common()

input:

1
2
3
# 接續上一個例子
print(count_string.most_common(1))
print(count_string.most_common(2))

output:

1
2
[('a', 4)]
[('a', 4), ('c', 2)]