簡體   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