1. 随机生成10000个100以内的正整数,找出其中出现次数最多的10个数及其出现次数。
random.randint(1,10) 产生 1 到 10 的一个整数型随机数
Counter(计数器):用于追踪值的出现次数 (以字典的键值对形式存储,key为被记录数,value为被记录数的个数)
sorted(c.items(), key=lambda x: x[1]) 中 c.items() 为待排序的对象,
key=lambda x: x[1] 为对前面的对象中的第二维数据(即value)的值进行排序,key=lambda x: x[0] 是对键(key)排序。
from collections import Counter
import random
intlist = []
for x in range(1,10001):
y = random.randint(1,100)
intlist.append(y)
intListCount = Counter(intlist)
intListCount1 = sorted(intListCount.items(), key=lambda q:q[1], reverse = True)
for z in range(0,6):
print(intListCount1[z], end=' ')
前为正整数,后为出现次数
(80, 129) (22, 127) (2, 122) (87, 120) (78, 118) (36, 114)
----------------------------------------------------------
本次习题较少,写三个做题过程中发现的一些有趣的小问题。
①
a = '' in 'hello'
b = ' ' in 'hello'
print(a)
print(b)
a是单引号里什么都没有,
b是单引号里有空格。
True
False
②同上
if '':
print('True')
else:
print('False')
False
if ' ':
print('True')
else:
print('False')
True
③
i = 5
for x in range(1, i):
print('{:<3}'.format(x), end='')
print('i=',i)
i += 2
1 i= 5
2 i= 7
3 i= 9
4 i= 11
i = 1
for x in range(i, 6):
print('{:<3}'.format(x), end='')
print('i=',i)
i += 3
1 i= 1
2 i= 4
3 i= 7
4 i= 10
5 i= 13