寻找一种更简洁的方法将值添加到空列表 Python

时间:2021-03-20 09:33:24

标签: python python-3.x list

我是 Python 新手,虽然我的任务被认为是正确的,但我知道有一种更有效的方法来编写代码,并且正在寻求建议。

我的目标是计算掷骰子的分数(1-6 之间)并将每个数字分配到一个列表中。在这种情况下,我知道掷骰子的值 'N' - 1 将是将其添加到列表的索引,但我不确定如何编写它。

import random

dice = [0]*6
for roll in range(1001): 
N = random.randint(1,6)
if N == 1:
    dice[0] = dice[0] + 1
if N == 2:
    dice[1] = dice[1] + 1
if N == 3:
    dice[2] = dice[2] + 1
if N == 4:
    dice[3] = dice[3] + 1
if N == 5:
    dice[4] = dice[4] + 1
if N == 6:
    dice[5] = dice[5] + 1
print(f' the number of times the dice rolled 1-6 is as follows {dice}')

4 个答案:

答案 0 :(得分:1)

您可以使用 N-1 作为列表的索引。

dice[N-1] += 1

答案 1 :(得分:1)

在处理随机值列表时,我推荐使用 numpy:

import numpy as np
_, counts = np.unique(np.random.randint(1,7, 1000), return_counts=True)

答案 2 :(得分:0)

给你:

dice = [0]*6
for roll in range(1001):
    dice[random.randint(0, 5)] += 1
print(f' the number of times the dice rolled 1-6 is as follows {dice}')

该列表正在使用 N-1 编制索引。

答案 3 :(得分:0)

import random
a = random.sample(range(1, 1001), 6)
print(a)

这可以简要介绍您正在寻找的更多内容 https://pynative.com/python-random-sample/