Contains of HashSet in Python

后端 未结 2 1784
渐次进展
渐次进展 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:42

    Just use a set:

    >>> l = set()
    >>> l.add(1)
    >>> l.add(2)
    >>> 1 in l
    True
    >>> 34 in l
    False
    

    The same works for lists:

    >>> ll = [1,2,3]
    >>> 2 in ll
    True
    >>> 23 in ll
    False
    

    Edit: Note @bholagabbar's comment below that the time complexity for in checks in lists and tuples is O(n) on average (see the python docs here), whereas for sets it is on average O(1) (worst case also O(n), but is very uncommon and might only happen if __hash__ is implemented poorly).

提交回复
热议问题