找出列表中重复的元素及个数

方法一: 将数组转成集合,然后循环
data = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 9]
lis = set(data)
for i in lis:
if data.count(i) > 1:
print('data数组中重复的元素是%d,它的个数是%d个' % (i, data.count(i)))

方法二: 定义空字典,将value的值大于1的添加到空字典里,然后循环字典的key和value
data = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 9]
a = {}
for i in data:
if data.count(i) > 1:
a[i] = data.count(i) # i是key,data.count(i)是value
for j, k in a.items():
print('data数组中重复的元素有%d,它的个数是%d个' % (j, k))

方法三: 不用count方法,循环判断空字典里如果有key,就对该key的value加1,没有key就让该key的value等于1,可以用while循环,也可以for循环
def get_element(data):
dic = {}
i = 0
while i < len(data):
if data[i] in dic:
dic[data[i]] += 1
else:
dic[data[i]] = 1
i += 1
for j, k in dic.items():
if k > 1:
print('data数组中重复的元素有%d,它的个数是%d个' % (j, k))


my_list = [1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4]
get_element(my_list)

==============================
def get_element(data):
dic = {}
for i in range(len(data)):
if data[i] in dic:
dic[data[i]] += 1
else:
dic[data[i]] = 1
for k, v in dic.items():
if v > 1:
print('列表中重复的元素是:%d,数量是%d' % (k, v))


data_list = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 9]
get_element(data_list)
posted @ 2019-07-08 11:41  laosun0204  阅读(3259)  评论(0编辑  收藏  举报