简体   繁体   中英

Changing an object's attribute in a list during iteration with Python

In Python, I'm trying to use nested for loops in my script to iterate over a list of object attributes. The iterated copy of the attribute resets during nested iteration. How can I modify the referenced object's attribute so that it doesn't reset?

class Player:
    def __init__(self, index, name, rating, sex, team, bench):
        self.index = index
        self.name = name
        self.rating = rating
        self.sex = sex
        self.team = team
        self.bench = bench

player1 = Player(1, "jasan", 971, "male", "MK", True)
player2 = Player(2, "Jaimen", 972, "male", "MK", True)
player3 = Player(3, "Jessica", 973, "female", "MK", True)
player4 = Player(4, "Justin", 904, "male", "MK", True)

opponent1 = Player(1, "Marc", 91, "male", "OPP", True)
opponent2 = Player(2, "Tom", 92, "male", "OPP", True)
opponent3 = Player(3, "Josh", 93, "male", "OPP", True)
opponent4 = Player(4, "Randy", 94, "male", "OPP", True)

mkroster = [player1, player2, player3, player4]
opproster = [opponent1, opponent2, opponent3, opponent4]

for x1 in mkroster:
    for y1 in opproster:
        x1.bench = False
        y1.bench = False
        for y2 in opproster:
            for x2 in mkroster:
                if x2.bench and y2.bench:
                    print(x1.bench, x2.bench)
                    match2 = matchup(x2.rating, y2.rating)
                    print("Round 2", x2.rating, y2.rating)
                    x1.bench = False
                    y1.bench = False
                    x2.bench = False
                    y2.bench = False
                    for x3 in mkroster:
                        for y3 in opproster:
                            if x3.bench and y3.bench:

    

How can I modify the object attribute ( player1.bench ) to match the iteration value ( x.bench )?

It looks to me like you are trying to do the work of the for loop. Like Chris Schmitz said, it looks like an anti-pattern. Check out this for a better idea of how the for loop assigns each value in your list to the variable, for instance, x1.

[EDIT] I'm not exactly sure what your code is trying to do, but here is a snippet and an explanation of some code that might help:

mkroster = [...]

opproster = [...]

for x1 in mkroster:
    for y1 in opproster:
        print(x1.name, y1.name)

What this code snippet prints out is

jasan, Marc
jasan, Tom
jasan, Josh
jasan, Randy
Jaimen, Marc
...

so x1 and y1 are already being assigned to each player object one at a time. If you want to have more complicated bracket that isn't just the roster in order you will need some more firepower.

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