我正在使用列表来跟踪数字,并希望将列表索引与随机数匹配,因此我可以从该索引的值中减去1。
import random
race_length = int(input("Choose the Length You Would Like You Race To Be
(Between 5 and 15)"))
dice = ["1", "2", "3", "4", "5", "6" ]
cars=[
["1", race_length],
["2", race_length],
["3", race_length],
["4", race_length],
["5", race_length],
["6", race_length],
]
while race_length >0:
print("Press Enter to Roll the Dice")
input()
chosen = int(random.choice(dice))
print(int(chosen))
我该怎么办,这样我才能将所选的匹配项与列表中的数字进行匹配
答案 0 :(得分:0)
无需与列表匹配,只需从列表中选择
import random
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15)"))
cars=[
["1", race_length],
["2", race_length],
["3", race_length],
["4", race_length],
["5", race_length],
["6", race_length],
]
while race_length >0:
print("Press Enter to Roll the Dice")
input()
chosen = random.choice(cars)
print(chosen[0])
chosen[1]-=1
您也将int方式转换为很多。因此print(int(“ 1”))会将“ 1”强制转换为1,然后又将其再次转换为“ 1”。
编辑:从选定项中减去一个可以简单地通过从索引1的选定字段中减去一个来完成。
答案 1 :(得分:0)
...想要使列表索引与随机数匹配,所以我可以从该索引的值中减去1。
您不需要在cars
中与每个元素一起添加索引。创建一个普通列表:
cars = [race_length] * len(dice)
索引并减去为:
cars[chosen-1] -= 1
代码:
import random
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15)"))
dice = ["1", "2", "3", "4", "5", "6" ]
cars = [race_length] * len(dice)
while race_length >0:
print("Press Enter to Roll the Dice")
input()
chosen = int(random.choice(dice))
print(chosen)
cars[chosen-1] -= 1
print(cars)
但这将达到无穷大,用户必须终止自己的程序。