Python初学者, 刚好有一个习题可以练手.就做了一下. 大概就是获取随机数,统计重复和不重复的数值.我目前所学到的我都用上了, 不知道还有没有一些可以优化的地方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import random import datetime lst = [] s = int(input("Starting from <<<")) # 随机数开始 e = int(input("To the end of the <<<")) # 随机数结束 c = int(input("How many numbers do you want <<<")) # 获取个数 start = datetime.datetime.now() # 获取开始时间 single = [] repeat = [] mart = [] # 先获取随机数 for i in range(c): lst.append(random.randint(s, e)) #统计随机数并分别创建列表 for x in lst: if x in mart: #加判定,如果已经count过的数值,不再继续重复计数 (为了减少count的次数,减少运行时间) continue else: mart.append(x) tol = lst.count(x) if tol == 1: single.append(x) else: repeat.append(x) print("The random values are {}".format(lst)) # 随机获取到的数值 print("The single values are {}".format(single)) # 单次出现的数值 print("The repeat values are {}".format(repeat)) # 多次出现的数值 print((datetime.datetime.now() - start).total_seconds()) # 运行时间 |