简体   繁体   中英

understanding a python snippet about a boolean variable

I beginner in python & I don't know this line in the following is used for what? It's a Boolean value?(for & if in a sentence?) If anybody know it, please explain. Thanks

taken_match = [couple for couple in tentative_engagements if woman in couple]


###
for woman in preferred_rankings_men[man]:
    #Boolean for whether woman is taken or not
    taken_match = [couple for couple in tentative_engagements if woman in couple]
    if (len(taken_match) == 0):
        #tentatively engage the man and woman
        tentative_engagements.append([man, woman])
        free_men.remove(man)
        print('%s is no longer a free man and is now tentatively engaged to %s'%(man, woman))
        break
    elif (len(taken_match) > 0):
        ...

Python has some pretty sweet syntax to create lists quickly. What you're seeing here is list comprehension-

    taken_match = [couple for couple in tentative_engagements if woman in couple]

taken_match will be a list of all the couples where the woman is in the couple- basically, this filters out all the couples where the woman is NOT in the couple.

If we were to write this out without list comprehension:

taken_match = []
for couple in couples:
     if woman in couple:
         taken_match.append(couple)

As you can see.. list comprehension is way cooler :)

After that line, you're checking if the length of the taken_match is 0- if it is, no couples were found with that woman in them, so we add in an engagement between what the man and the woman, and then move on. If you have any other lines you didn't understand, feel free to ask!

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