Contains of HashSet in Python

后端 未结 2 1783
渐次进展
渐次进展 2020-12-15 14:59

In Java we have HashSet, I need similar structure in Python to use contains like below:

A = [1, 2, 3]
S = set()
S.add(2)
for x in         


        
2条回答
  •  一整个雨季
    2020-12-15 15:37

    In Python, there is a built-in type, set. The major difference from the hashmap in Java is that the Python set is not typed, i.e., it is legal to have a set {'2', 2} in Python.

    Out of the box, the class set does not have a contains() method implemented. We typically use the Python keyword in to do what you want, i.e.,

    A = [1, 2, 3]
    S = set()
    S.add(2)
    for x in A:
      if x in S:
        print("Example")
    

    If that does not work for you, you can invoke the special method __contains__(), which is NOT encouraged.

    A = [1, 2, 3]
    S = set()
    S.add(2)
    for x in A:
      if S.__contains__(x):
        print("Example")
    

提交回复
热议问题