【问题标题】:All possible outcomes, loop required [duplicate]所有可能的结果,需要循环[重复]
【发布时间】:2016-04-07 05:39:06
【问题描述】:

我有一份所有英超球队的名单:

teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ]

我需要计算所有可能的 team1-vs-team2 配对。

目前我有以下代码:

oppo = 0

for team in teamlist:
        print team + "-vs-" + teamlist[oppo]
        oppo+=1
        print team + "-vs-" + teamlist[oppo]
        oppo+=1

将输出:

arsenal-vs-arsenal
arsenal-vs-aston-villa

但是我需要这个遍历每支球队,显示他们所有可能的主场比赛赛程,然后移动到球队列表中的下一个球队,输出他们所有可能的主场比赛赛程并重复直到所有球队都完成。

【问题讨论】:

    标签: python loops if-statement for-loop while-loop


    【解决方案1】:

    在函数中递归执行此操作应该可行。

    # after defining teamlist
    
    def printVS(start):
        for x in range(1,len(teamlist)-start):
            print teamlist[start],"vs",teamlist[start+x]
        if start < len(teamlist):
            printVS(start+1)
    
    printVS(0)
    

    【讨论】:

      【解决方案2】:

      这可以通过循环遍历团队列表两次并检查对手是否“在”原始团队“之前”来存档。 代码也不依赖于外部库。

      teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ]
      
      for team in teamlist:
          for opponent in teamlist:
              if team < opponent:
                  print(team + "-vs-" + opponent)
      

      【讨论】:

      • 使用此解决方案,您将得到重复的反向“-vs-”。
      • 我想这行得通... :) 我会从0..len 然后i+1..len 做一个循环
      【解决方案3】:

      嵌套for 循环的替代方法是从列表中的项目中计算所有长度为 2 的排列。

      >>> from itertools import permutations
      >>> for team1, team2 in permutations(teamlist, 2):
      ...     print '{0} -vs- {1}'.format(team1, team2)
      ... 
      arsenal -vs- aston-villa
      arsenal -vs- bournemouth
      arsenal -vs- chelsea
      # and so on ...
      

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 1970-01-01
        • 2016-03-29
        • 2014-04-24
        • 2013-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        相关资源
        最近更新 更多