简体   繁体   English

Python:从集合中提取元素

[英]Python: Extract element from set

I have a class: 我有一堂课:

class MyClass:
    def__init__( self, name : str ) -> None:
        self.__name : str = name
        self.extra : object = None

    def __eq__( self, other : object ) -> bool:
        if not isinstance( other, MyClass ):
            return False

        return self.__name == other.__name

    def __hash__( self ) -> int:
        return hash( self.__name )

Thus __name is immutable and two MyClass es are equal if they share the same __name . 因此__name是不可变的,并且如果两个MyClass共享相同的__name则它们相等。

I have a set defined thus: 我这样定义了一个集合:

eggs = MyClass( "eggs" )
beans = MyClass( "beans" )
spam = MyClass( "spam" )
c.extra = "spam spam spam"
my_set : Set[MyClass] = { eggs, beans, spam }

I can test if spam is in my set: 我可以测试spam是否存在:

has_spam : bool = MyClass( "spam" ) in my_set 

But how to I get "spam.extra" by the name? 但是,如何获得“ spam.extra”这个名称呢? I could use a dict , but this requires duplicating the name property, or I could iterate, but this seems wasteful. 我可以使用dict ,但这需要复制name属性,或者可以迭代,但这似乎很浪费。

There's no way to do what you want with a set that I know of (short of iterating over the whole thing). 我无法用一套我所知道的集合来做你想做的事情(没有遍历整个过程)。 As I understand it, the only way to get anything out of a set is to iterate over it or use set.pop , which gets you an arbitrary element of the set. 据我了解,从集合中获取任何内容的唯一方法是对其进行迭代或使用set.pop ,它使您可以获取集合中的任意元素。

You could use a dictionary to map what you've called __name to extra (and avoid using any custom class), ie 您可以使用字典将__nameextra (并避免使用任何自定义类),即

my_set = {"eggs": "some extra data", "beans": None, "spam": None}

This seems like exactly the case where you would want to use a dictionary, unless there are more requirements you haven't mentioned. 除非您没有提到更多要求,否则这似乎就像您要使用字典的情况一样。

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

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