生成100个2位随机正整数
生成100个2位随机正整数,按每行十个输出,并求出个位数字分别为0,1,2,3,4,5,6,7,8,9的正整数的个数
解题思路:
1、2位随机正整数:范围是[10,99],利用random.randint()生成100个随机数,存入random_list,即random_list[0]至random_list[99];
2、生成待对比的统计字典集,statistics = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0};
3、利用enumerate()函数生成数据及其数据位置索引的字典集合:
for index, x in enumerate(random_list)
4、print(x, end=' '):end参数用法
python里的end是print函数中的参数,为末尾end传递一个字符串,这样print函数不会在字符串末尾添加一个换行符,而是添加一个字符串,其实这也是一个语法要求,表示这个语句没结束。
选项代码:
dom
def fun():
random_list = [random.randint(10, 99) for n in range(100)]
statistics = {n: 0 for n in range(10)}
for index, x in enumerate(random_list):
print(x, end=' ')
#统计key出现的次数,若出现key的值加1
statistics[int(x % 10)] = statistics[int(x % 10)] + 1
#每10个数值打印一个换行符
if ((index + 1) % 10 == 0):
print()
print(statistics)
if __name__ == '__main__':
fun()
Python random randint() 方法
https://www.runoob.com/python3/ref-random-randint.html
Python random.randint() 方法返回指定范围内的整数。
randint(start, stop) 等价于 randrange(start, stop+1)。
语法
random.randint() 方法语法如下:
random.randint(start, stop)
参数start是下限,参数stop是上限,生成的随机数n: start <= n <= stop
参数说明:
- start -- 必需, 一个整数,指定开始值。
- stop -- 必需, 一个整数,指定结束值。
返回值
返回指定范围内的整数。
实例
以下实例返回一个 1 到 9 之间的数字(大于等于 1,小于等于 9 ):
实例
# 导入 random 包
import random
# 返回一个 1 到 9 之间的数字
print(random.randint(1, 9))
输出结果:
8
Python enumerate() 函数
https://www.runoob.com/python/python-func-enumerate.html
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标(这里的数据下标也可以理解为索引位置),一般用在 for 循环当中。
Python 2.3. 以上版本可用,2.6 添加 start 参数。
语法
以下是 enumerate() 方法的语法:
enumerate(sequence, [start=0])
参数
- sequence -- 一个序列、迭代器或其他支持迭代对象。
- start -- 下标起始位置的值。
返回值
返回 enumerate(枚举) 对象。
实例
以下展示了使用 enumerate() 方法的实例:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的 for 循环
>>> i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
... print i, seq[i]
... i += 1
...
0 one
1 two
2 three
for 循环使用 enumerate
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three