一、怎么得到列表中每個元素的重復次數:
方法: 可以得到列表中元素出現的次數
#列表名.count(列表中元素)
a1 = [1,2,2,2,2,3,3,3,4,4,4,4] print(a1.count(2)) #output:4
鑒於此:我們可以得到每個元素的出現次數
a1 = [1,2,2,2,2,3,3,3,4,4,4,4] a_count = [] for i in a1: a_count.append(a1.count(i)) print(a_count) #[1, 4, 4, 4, 4, 3, 3, 3, 4, 4, 4, 4]
二、有沒有一種就是返回不重復元素和次數的方法呢?比如:{(1:1),(2:4),(3,3),(4,4)}的方法?
答案是有的,但是順序不是我們要的順序。這不就是我們要的結果嗎?只是順序不一樣,無所謂吧!
方法:
collections.Counter(列表)
>>> from collections import Counter >>> Counter([1,2,2,2,2,3,3,3,4,4,4,4]) Counter({2: 4, 4: 4, 3: 3, 1: 1})
>>> type(Counter([1,2,2,2,2,3,3,3,4,4,4,4])) <class 'collections.Counter'>
那這個 collections.Counter 類型的東西怎么操作呢?字典的很多操作都是可以的!
>>> from collections import Counter >>> a = Counter([1,2,2,2,2,3,3,3,4,4,4,4]) >>> dict(a)#可以將其轉換字典 {1: 1, 2: 4, 3: 3, 4: 4} >>> a.values()#直接查看變量值 dict_values([1, 4, 3, 4]) >>> a.keys()#直接查看key值 dict_keys([1, 2, 3, 4]) >>> sum(a.values()) 12 >>> sum(a.keys()) #鍵值以及變量的求和 10 >>> set(a)#集合操作 {1, 2, 3, 4} >>> a Counter({2: 4, 4: 4, 3: 3, 1: 1}) >>> a.items() dict_items([(1, 1), (2, 4), (3, 3), (4, 4)]) >>> list(a.items()) [(1, 1), (2, 4), (3, 3), (4, 4)] #這不就是我們尋找的結果嗎? >>>
#Python 字典(Dictionary) items() 函數以列表返回可遍歷的(鍵, 值) 元組數組。
三、我就想要不重復也要排好順序的?來,有!
方法:
#將元素與其對應的重復次數合並后順序去除重復元素
#順序的方法:回列表元組 a1 = [1,2,2,2,2,3,3,3,4,4,4,4] a_count = [] for i in a1: a_count.append(a1.count(i)) #將元素與其對應的重復次數合並 l_sum = zip(a1,a_count) #最后去除重復元素 a1_unique = [] for (i,j) in l_sum: if (i,j) not in a1_unique: a1_unique.append((i,j)) print(a1_unique)
#output:[(1, 1), (2, 4), (3, 3), (4, 4)]
參考代碼:
列表名.count(列表中元素):https://www.jb51.net/article/53911.htm
collections.Counter(列表) :
https://www.cnblogs.com/keke-xiaoxiami/p/8553076.html
https://www.cnblogs.com/hycstar/p/9345751.html
字典.items: https://www.runoob.com/python/att-dictionary-items.html