繁体   English   中英

从列表中获取所有可能的组合作为元组

[英]Get all possible combinations from a list as tuples

上下文:我正在学习 python 并且我正在尝试在不使用 itertools 的情况下进行排列。 我有一个包含 3 个足球队的列表,我想在他们之间进行所有可能的比赛(因此,对于team列表中的 3 支team ,我们将有 6 场可能的比赛,4 支球队将是 12 场比赛,等等)。

我试图做这样的事情:

team = ["FCP", "SCP", "SLB"]

def allMatches(lst):
    teams = []
    for index in range(0,len(lst)-1):
        for element in lst:
            if teams[index][0] != teams[index][1]: #I was trying to make it so that tuples that have the same team are excluded - ('FCP','FCP') would not be appended for example, but I'm calling teams when it has 0 items appended so this won't do nothing
                teams.append(tuple((element,team[index-1])))
    return teams

allMatches(team)

所需的输出将是这样的:

[('FCP','SCP'), ('FCP','SLB'), ('SCP','FCP'), ...]

先感谢您

这将修复您的代码:

team = ["FCP", "SCP", "SLB"]
def allMatches(lst):
    teams = []
    for element_list1 in lst:
        for element_list2 in lst:
            if element_list1 != element_list2:
                teams.append(tuple((element_list1, element_list2)))
    return teams

allMatches(team)

使用列表理解会更好:

team = ["FCP", "SCP", "SLB"]
def allMatches(lst):
    return [(el1, el2) for el1 in lst for el2 in lst if el1!=el2]
    

allMatches(team)

你可以试试这个:

team = ["FCP", "SCP", "SLB"]
teams = []

for index in range(len(team)) :
    for index_2 in range(len(team)) :
        if index != index_2 :
            teams.append(tuple((team[index], team[index_2])))

print(teams)

#[('FCP', 'SCP'),('FCP', 'SLB'),('SCP', 'FCP'),('SCP', 'SLB'),('SLB', 'FCP'),('SLB', 'SCP')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM