用Python列出 - 试图消除加倍的条目

时间:2014-03-03 04:23:32

标签: python list

我有一个问题,我在互联网上没有找到任何答案(它是在python上):

我有一个名为Pion的类,如下所示:

class Pion():
    def __init__(self,x,y):
        self.x = x
        self.y = y

在main函数中,我正在创建一个Pion列表:

PionList = []

我正在将这些值添加到此列表中:

PionList.append(Pion(3,4))
PionList.append(Pion(4,6))
PionList.append(Pion(3,4))
PionList.append(Pion(2,9))
PionList.append(Pion(4,6))

现在,我想找到一种清理列表的方法,并且只为列表的每个元素提供唯一的x和y组合属性,所以最后,我的列表将有3个元素而不是5个(我想要消除加倍条目(3,4)和(4,6),只有一个元素Pion(3,4),一个元素Pion(4,6)和一个元素Pion(2,9)

我试图在我的代码中实现它,但我无法想象我将如何处理。

这个问题的任何线索或可能的解决方案?

2 个答案:

答案 0 :(得分:4)

使用set

class Pion():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __repr__(self):
        return 'Pion({0.x},{0.y})'.format(self)

lst = [Pion(3,4), Pion(4,6), Pion(3,4), Pion(2,9), Pion(4,6)]

seen = set()
newlst = []
for pion in lst:
    key = pion.x, pion.y
    if key in seen:
        continue
    seen.add(key)
    newlst.append(pion)

print(newlst)

输出:

[Pion(3,4), Pion(4,6), Pion(2,9)]

如果您定义__hash____eq__,则可以更简单地执行此操作(无法保证元素的顺序)。

>>> class Pion():
...     def __init__(self,x,y):
...         self.x = x
...         self.y = y
...     def __repr__(self):
...         return 'Pion({0.x},{0.y})'.format(self)
...     def __hash__(self):
...         return hash((self.x, self.y))
...     def __eq__(self, other):
...         return self.x == other.x and self.y == other.y
...
>>> lst = [Pion(3,4), Pion(4,6), Pion(3,4), Pion(2,9), Pion(4,6)]
>>>
>>> list(set(lst))
[Pion(3,4), Pion(4,6), Pion(2,9)]

或者,您可以使用OrderedDict.fromkeys(订单已保留):

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lst))
[Pion(3,4), Pion(4,6), Pion(2,9)]

答案 1 :(得分:1)

这可以使用集合轻松解决。你只需要使你的Pion哈希能够,然后你可以这样做:

class Pion():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __key(self):
        return (self.x, self.y)

    def __hash__(self):
        return hash(self.__key())

    def __eq__(self, other):
        return self.__key() == other.__key()

PionSet = {Pion(3, 4),
           Pion(4, 6),
           Pion(3, 4),
           Pion(2, 9),
           Pion(4, 6)}

您可以使用add方法以编程方式添加更多内容。