簡體   English   中英

使用 Python 在迭代期間更改列表中對象的屬性

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

在 Python 中,我嘗試在腳本中使用嵌套的 for 循環來遍歷 object 屬性列表。 屬性的迭代副本在嵌套迭代期間重置。 如何修改引用對象的屬性使其不重置?

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:

    

如何修改 object 屬性 ( player1.bench ) 以匹配迭代值 ( x.bench )?

在我看來,您正在嘗試執行 for 循環的工作。 正如 Chris Schmitz 所說,它看起來像是一種反模式。 查看內容以更好地了解 for 循環如何將列表中的每個值分配給變量,例如 x1。

[編輯] 我不確定您的代碼要做什么,但這里有一個片段和一些可能有幫助的代碼的解釋:

mkroster = [...]

opproster = [...]

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

此代碼段打印出來的是

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

所以 x1 和 y1 已經被分配給每個玩家 object 一次。 如果您想擁有更復雜的支架,而不僅僅是花名冊,那么您將需要更多的火力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM