【问题标题】:selecting numbers from a list in python从python中的列表中选择数字
【发布时间】:2013-03-19 18:55:17
【问题描述】:

我正在开发一个生成单场淘汰锦标赛的程序。到目前为止我的代码看起来像这样(我刚刚开始)

amount = int(raw_input("How many teams are playing in this tournament?  "))
teams = []
i = 0
while i<amount:
    teams.append(raw_input("please enter team name:  "))
    i= i+1

现在我被困住了。我想随机选择 2 个数字来选择彼此面对的团队。这些数字根本不能重复,并且必须从 1 到“数量”。最有效的方法是什么?

【问题讨论】:

    标签: python list random


    【解决方案1】:

    我不完全确定你的要求是什么,但是选择你可以使用的随机数

    random.randint(1,10)
    

    这会给你一个介于 1 到 10 之间的随机数

    注意:需要导入随机模块

    import random
    

    【讨论】:

      【解决方案2】:
      team1 = random.choice(teams)
      teams.remove(team1)
      team2 = random.choice(teams)
      

      我认为应该可以。

      【讨论】:

      • 是的。在 Python 中,您可以只询问您真正想要的:随机选择的团队之一。无需获取随机数并使用它来获取团队,只需获取随机团队即可。
      • 这取决于您需要什么:这是一种从大于 2 的列表中选择 2 个团队的方法。如果您要留下一个团队,您将不得不无论您使用什么方法来配对团队,都要为他们做一个特殊的案例(给他们一个再见之类的东西)。
      【解决方案3】:

      看看random 模块。

      >>> import random
      >>> teams = ['One team', 'Another team', 'A third team']
      >>> team1, team2 = random.sample(teams, 2)
      >>> print team1
      'Another team'
      >>> print team2
      'One team'
      

      【讨论】:

      • 不错!我检查了文档,random.sample() 将从列表中返回两个唯一值。因此,只要每个团队名称在列表中出现一次,就可以保证随机选择两个不同的团队名称。我认为没有比这更好的解决方案了!
      • @user2108568 不客气 :)。不要忘记接受答案:)。
      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      相关资源
      最近更新 更多