python学习习题总结(6)——统计重复数和非重复数,列表,字典

#随机生成若干数字 统计重复数和非重复数,按顺序输出 ||例50个[100,200]的数
import random
#lst = [randome.randint(100,200) for i in range(50)]    同append,效率比乘法*一次开辟空间慢
lst = [0]*50
for i in range(50):
    lst[i] = random.randint(100,200)
print('Random numbers:{}'.format(','.join(map(str,lst))))
print('Method one:')
##局限性大,数组索引记录值
lst1 = [0]*201
for i in lst:
    lst1[i] += 1
repenum = []
no_repenum = []
for i in range(len(lst1)):
    if lst1[i] == 1:
        no_repenum.append(i)
    if lst1[i] >1:
        repenum.append((i,lst1[i]))
print('The no-repetition numbers is :{}'.format(','.join(map(str,no_repenum))))
print('The repetition numbers is :{}'.format(','.join(map(str,repenum))))
print(no_repenum,repenum)
print('~~~~~~~~~~~~~~~~~~~~~~~~'*5)
print('Method two:')
##新建一个计数列表,一一对应,重复的数打标记,在第一个不重复的数上计数
lst2 = [0]*50
repenum = []
no_repenum = []
for i in range(len(lst)):
    if lst2[i] != 0:
        continue
    else:
        lst2[i] = 1
    for j in range(i+1,len(lst)):
        if lst2[j] != 0:
            continue
        if lst[i] == lst[j]:
            lst2[i] += 1
            lst2[j] = 1
    if lst2[i] == 1:
        no_repenum.append(lst[i])
    else:
        repenum.append((lst[i],lst2[i]))
print(sorted(no_repenum),sorted(repenum))
print('~~~~~~~~~~~~~~~~~~~~~~~~'*5)
print('Method three:')
#遍历每一个数,相同的数放入一个数组
lst3 = []
repenum = []
no_repenum = []
for i in range(len(lst)):
    flag = False
    for j in range(len(lst3)):
        if lst[i] in lst3[j]:
            lst3[j].append(lst[i])
            flag = True
    if flag == False:
        lst3.append([lst[i]])
for i in range(len(lst3)):
    if len(lst3[i]) == 1:
        no_repenum.append(lst3[i][0])
    else:
        repenum.append((lst3[i][0],len(lst3[i])))
print(sorted(no_repenum),sorted(repenum))
print('~~~~~~~~~~~~~~~~~~~~~~~'*5)
print('Method four:')
#先把列表排序,重复数在一起,分别计数,统计过的变为None
lst4 = sorted(lst)
no_repenum = []
repenum = []
for i in range(len(lst4)):
    if lst4[i] == None:
        continue
    for j in range(i+1,len(lst4)):
        if lst4[j] != lst4[i]:
            if j - i == 1:
                no_repenum.append(lst4[i])
                lst4[i] = None
            else:
                repenum.append((lst4[i],j-i))
                for x in range(i,j):
                    lst4[x] = None
            break
    else:
        if i == len(lst4)-1:
            no_repenum.append(lst4[i])
        else:
            repenum.append((lst4[i],len(lst4)-i))
        break
print(no_repenum,repenum)
print('~~~~~~~~~~~~~~~~~~~~~~'*5)
print('Method five')
#字典
dic = {}
no_repenum = []
repenum = []
for i in sorted(lst):
    dic[i] = dic.get(i,0)+1 
for i in dic:                         #python 3.6 字典有序输出
    if dic[i] == 1:
        no_repenum.append(i)
    else:
        repenum.append((i,dic[i]))
print(no_repenum,repenum)
print('~~~~~~~~~~~~~~~~~~~~~'*5)
print('Method six')
#count方法,效率最低,抛弃

猜你喜欢

转载自blog.csdn.net/qq_33287645/article/details/79815709
今日推荐