【问题标题】:How to match a random number with a number from a list如何将随机数与列表中的数字匹配
【发布时间】:2019-08-22 09:01:22
【问题描述】:

我正在使用列表来跟踪数字,并希望将列表索引与随机数匹配,以便我可以从该索引的值中减去 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))

我该怎么做才能将所选的匹配项与我列表中的数字匹配

【问题讨论】:

    标签: python list random


    【解决方案1】:

    ...想要将列表索引与随机数匹配,以便我可以从该索引的值中减去 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)
    

    但这将无限期结束,用户必须终止自己的程序。

    【讨论】:

    • 在我的实际程序中,我有一种停止的方式,但是我想为所有 6 个“数字”分别更改比赛长度的值
    • 不确定“单独”是什么意思?
    • 能够改变不同索引的race_length值,比如列表中的2。
    • 反对无穷大:while min(cars) > 0:
    • 他从未说明race_length 是如何减少的。也许它是所有汽车特定种族长度的最小值
    【解决方案2】:

    无需与列表匹配,只需从列表中选择

    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
    

    你也投了很多。所以 print(int("1")) 会将 "1" 转换为 1,然后再将其转换为 "1"。

    编辑:从选择的字段中减去一个可以简单地通过从索引 1 处的选择字段中减去一个来完成。

    【讨论】:

    • 我需要匹配它们,因为我需要确定从比赛距离中减去 1 的距离
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2021-10-04
    • 2014-09-28
    相关资源
    最近更新 更多