我正在使用列表来跟踪数字,并希望将列表索引与随机数匹配,以便我可以从该索引的值中减去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))
我该怎么做才能将所选匹配与我列表中的数字相匹配
...想要使用随机数匹配列表索引,这样我就可以从该索引的值中减去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)
但这是无限的,用户必须自己终止程序。
没有必要与列表匹配只需从列表中选择
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处的选择字段中减去一个来完成。