列出索引超出范围-IndexError

时间:2018-12-29 20:00:08

标签: python

我试图在Python上模拟Monopoly,但是当我尝试让骰子掷出1到6之间的随机数时。

from random import randint

dice_numbers = [1,2,3,4,5,6]
dice1 = dice_numbers[randint(0, 6)]
dice2 = dice_numbers[randint(0, 6)]

掷骰子时,其中一个骰子数字是6,它附带一个

  

Indexerror:列表索引超出范围

我通过打印数字来测试它是否是数字6。

print(dice1, dice2)

所有数字都很好,但我一次也没有看到6。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

出现索引错误是因为生成的索引范围是1到6,列表的索引从0开始到6:

[1 , 2 , 3 , 4 , 5 , 6]   # list
 0   1   2   3   4   5    # index

您创建一个随机索引来索引一个数字列表以从中获取数字...太复杂了。您不需要数字列表-您可以直接创建所需的数字。

要获取随机整数,请使用

import random

print( random.randint(1,6) )  # one integer between 1 and 6 (inclusivly)

要从可迭代使用中获取一个元素

print( random.choice( [1,2,3,4,5,6] ) )  # chooses one element randomly

要获取 a b 之间的随机数,您也可以使用

a = 1
b = 6  # range(a,b) is exclusively - you need to add 1 to the upper limit to include it
print (random.choice( range(a, b+1) ) )  # return one number from the range [a,..,b]

要从可重复使用中获取多个值

print( random.choices( range( 1, 7), k= 100) ) # return 100 numbers as list between 1 and 6

您可以在此处找到整个随机文档:python.org: module random