简体   繁体   English

避免在python列表中重复

[英]Avoiding duplication in a python list

I'm trying to put together a bit of logic for a chess game and have gotten stuck with making sure I don't place multiple pieces on the same square. 我试图为国际象棋游戏整理一些逻辑,并努力确保不会在同一方块上放置多个棋子。 My code at the moment is as follows but I'm not sure where it's not working. 目前,我的代码如下,但是我不确定它在哪里不起作用。

def add(self, pawn, x_coordinate, y_coordinate, piece_color):
        for each_pawn in self.pawns:
            if each_pawn.x_coordinate == x_coordinate and each_pawn.y_coordinate == y_coordinate:
                pawn.x_coordinate = -1
                pawn.y_coordinate = -1
            else:
                pawn.x_coordinate = x_coordinate
                pawn.y_coordinate = y_coordinate

        self.pawns.append(pawn)

Pawns is set as an empty list at the top of the class. 典当在类的顶部设置为空列表。 The idea is that the pawn I'm creating goes into the list then when any subsequent ones are created it is checking for them having the same coordinates, if it does it is placed in the -1, -1 square ie off the board. 这个想法是,我要创建的棋子进入列表,然后在创建任何后续棋子时检查它们是否具有相同的坐标,如果确实放置,则将其放置在-1,-1正方形内,即不在板上。 I'm sure it's not particularly elegant but I'm new with Python and hope to come back and refactor when I have some fundamentals working. 我敢肯定它不是特别优雅,但是我是Python的新手,希望当我有一些基础知识工作时再回来重构。 Thanks for any help! 谢谢你的帮助!

At the end of the loop pawn 's coordinates will correspond to result from the last pawn it was tested against. 在循环的末尾, pawn的坐标将对应于对其进行测试的最后一个pawn的结果。 Add a break statement after pawn.y_coordinate = -1 . pawn.y_coordinate = -1之后添加break语句。

class Pawn:
    def __init(x, y):
        self.x_coordinate = x
        self.y_coordinate = y

    @property
    def x_coordinate(self):
        return self.x_coordinate

    @x_coordinate.setter
    def x_corrdinate(x):
        self.x_coordinate = x    

    @property
    def y_coordinate(self):
        return self.y_coordinate

    @y_coordinate.setter
    def y_corrdinate(y):
        self.y_coordinate = y

    def __hash__(self):
        return hash(self.x_coordinate) ^ hash(self.y_coordinate)

    def __eq__(self, other):
        return self.x_coordinate == other. x_coordinate and self.x_coordinate == other.y_coordinate

Basically, write a class Pawn which has x and y coordinates, override __eq__() method and __hash__() , they would be used when check if pawn not in pawns: the __eq__() is used to validate 2 Pawn instance are equal or not based on their x and y coordinates. 基本上,写一个类兵其具有x和y坐标,重写__eq__()方法和__hash__()它们将在检查中使用if pawn not in pawns:所述__eq__()是用来验证2兵实例是相等的或不根据它们的x和y坐标。

How to use? 如何使用?

pawn = Pawn(-1, -1)
if pawn not in pawns:
    pawns.append(pawn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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