Context: I'm learning python and I'm trying to make permutations without using itertools. I have a list with 3 football teams and I'd like to make all possible matches between them (so with 3 teams from the team
list, we would have 6 possible matches, 4 teams would be 12 matches, etc).
I was trying to do something like this:
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)
Desired output would be something like this:
[('FCP','SCP'), ('FCP','SLB'), ('SCP','FCP'), ...]
Thank you in advance
This would fix your code:
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)
It would be even nicer with a list comprehension:
team = ["FCP", "SCP", "SLB"]
def allMatches(lst):
return [(el1, el2) for el1 in lst for el2 in lst if el1!=el2]
allMatches(team)
You can try this :
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.