一、怎么得到列表中每个元素的重复次数:
方法: 可以得到列表中元素出现的次数
#列表名.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