【问题标题】:Secrets: removing generated variables from a previously defined list?秘密:从先前定义的列表中删除生成的变量?
【发布时间】:2021-09-24 08:00:06
【问题描述】:

我正在使用秘密从先前定义的列表中获取两个随机变量。我需要连续做两次。第二次,我需要程序从同一个列表中进行选择,除了选择第一次返回的两个。

num_to_select = 2
unassigned_cards = [2,3,4,5,6,7,8,9,10,10,10,10,'ACE']
draw_cards = 4*unassigned_cards
dealers_cards = secure_random.sample(draw_cards, num_to_select)
draw_cards.remove(dealers_cards)()
players_cards = secure_random.sample(draw_cards, num_to_select)

出现此错误消息是可以理解的,因为我已要求它删除原始列表中不存在的对象。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-0d34b9c572c9> in <module>
      1 dealers_cards = secure_random.sample(draw_cards, num_to_select)
----> 2 draw_cards.remove(dealers_cards)()
      3 players_cards = secure_random.sample(draw_cards, num_to_select)
      4 
      5 print('Dealer drew', dealers_cards,'for a total of', sum(dealers_cards))

ValueError: list.remove(x): x not in list

为了澄清,这是一场纸牌游戏,所以我在第三行代码中将列表乘以 4 以表示四套花色,因此从列表中删除“庄家的牌”只会降低抽奖的可能性一个特定的数字,而不是让它完全不可能。

请解释我在哪里出错了。

【问题讨论】:

    标签: python list variables


    【解决方案1】:

    好的,所以这里的问题是 sample 返回一个包含(在你的情况下)2个值的列表,所以你需要做下一个:

    dealers_cards = draw_cards[randint(0, len(draw_cards)-1)]
    draw_cards.remove(dealers_cards)
    

    在这里,您从列表中随机抽取一张卡片,然后将其移除,如果您想移除 2 张卡片,您可以使用 for 循环来完成。它看起来像这样:

    for _ in range(2):
        dealers_card = draw_cards[randint(0, len(draw_cards)-1)]
        print(dealers_card)
        draw_cards.remove(dealers_card)
    

    【讨论】:

    • 感谢 Sergio,但我收到此错误消息(问题的在线解决方案只讨论未定义的变量,但“randint”不同,对吧?--------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-5-f49b63352079&gt; in &lt;module&gt; 1 for _ in range(2): ----&gt; 2 dealers_cards = draw_cards[randint(0, len(draw_cards)-1)] 3 print(dealers_card) 4 draw_cards.remove(dealers_card) NameError: name 'randint' is not defined
    • 我忘了提到您需要在代码开头添加from random import randint。这就是我用来生成随机整数的函数
    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 2021-11-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2014-03-08
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多