【问题标题】:Get all possible combinations from a list as tuples [duplicate]从列表中获取所有可能的组合作为元组[重复]
【发布时间】:2021-11-17 06:21:59
【问题描述】:

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

我试图做这样的事情:

团队 = [“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[0], team[1]), (team[0], team[2]), ...]
  • 以后请先尝试搜索解决方案。在您的情况下,就像输入 python combinations into a search engine 一样简单。
  • @KarlKnechtel 谢谢,我发现的大多数解决方案都使用了 itertools,我试图寻找尽可能“原版”的东西。
  • 该问题也有各种以前的重复,此外还有更多关于 Internet 其余部分的指导。试试python combinations without itertools
  • 会做的,谢谢你的帮助!

标签: python


【解决方案1】:

这将修复您的代码:

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)

【讨论】:

    【解决方案2】:

    你可以试试这个:

    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')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      相关资源
      最近更新 更多