简体   繁体   中英

How to go through a nested for loop?

Hello I am trying to make my code go through a nested for loop, but the loop refuses to follow my original construct of thought.

My code is shown below.

def couple(men_choice, women_choice):

possible_engagements = []

# men's first choice
for man in range(len(men_choice)):
    for woman in men_choice:
        pair = (man, woman[0])
        possible_engagements.append(pair)
    return possible_engagements

I am trying to design the first step of gale shapley algorithm, where each men will get paired with the first choice of woman in each of their list.

For example, if I have

>>> men_choice = [[1, 2, 3, 0], [3, 1, 2, 0], [2, 1, 3, 0], [3, 2, 0, 1]]

possible_engagements = [(0, 1), (0, 3), (0, 2), (0, 3)] # current output

possible_engagements = [(0, 1), (1, 3), (2, 2), (3, 3)] # desired output

Men's first choice of women are being outputted as I planned, but the index of men are not in sequence.

What problems do I have with my loop?

You only need one for loop to go through the mens choices, and to make sure you have no duplicate matchings, you have to check if the woman is already paired with another man.

def couple(men_choice, women_choice):

possible_engagements = []

# men's first choice
    for man in range(len(men_choice)):
            i = 0
            pair = (man, men_choice[i])
            while ([x[1] for x in possible_engagements].count(men_choice[i]) > 0):         #Check if woman is already chosen
                pair = (man, men_choice[i])
                i=i+1
            possible_engagements.append(pair)
    return possible_engagements

Your return keyword is located inside your outer loop. This means that man will only take the value 0, hence your current output. The code below achieves your desired output.

men_choice = [[1, 2, 3, 0], [3, 1, 2, 0], [2, 1, 3, 0], [3, 2, 0, 1]]
women_choice = []


def couple(men_choice, women_choice):
    possible_engagements = []
    for man in range(len(men_choice)):
        possible_engagements.append((man, men_choice[man][0]))
    return possible_engagements


possible_engagements = couple(men_choice, women_choice)
print(possible_engagements)

As a list comprehension:

def couple(men_choice, women_choice):
    return [(i, x[0]) for i, x in enumerate(men_choice)]

As a for-loop generator:

def couple(men_choice, women_choice):
    for i, x in enumerate(men_choice):
        yield (i, x[0])

As a for-loop + list.append:

def couple(men_choice, women_choice):
    engagements = []
    for i, x in enumerate(men_choice):
        engagements.append((i, x[0]))
    return engagements

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.

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