所有可能的结果,需要循环

时间:2016-01-03 13:34:25

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

我列出了所有英超联赛球队:

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

然而,我需要通过每个团队,显示他们所有可能的主场比赛设备,然后进入团队列表中的下一个团队,输出他们所有可能的主场比赛设备并重复直到所有球队都完成。

3 个答案:

答案 0 :(得分:8)

嵌套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 ...

答案 1 :(得分:3)

这可以通过两次循环队列并通过检查对手是否在"之前来实现。原来的团队。 代码也不依赖于外部库。

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)

答案 2 :(得分: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)