包含 Python 中的 HashSet<Integer>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26724002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Contains of HashSet<Integer> in Python
提问by Borys Stepov
In Java we have HashSet<Integer>, I need similar structure in Python to use contains like below:
在 Java 中HashSet<Integer>,我需要在 Python 中使用类似的结构,如下所示:
A = [1, 2, 3]
S = set()
S.add(2)
for x in A:
if S.contains(x):
print "Example"
Could you please help?
能否请你帮忙?
回答by tttthomasssss
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 inchecks 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).
编辑:请注意下面@bholagabbar 的评论,in检查列表和元组的时间复杂度平均为 O(n)(请参阅此处的 Python 文档),而对于集合,它平均为 O(1)(最坏的情况也是 O(n) ),但非常罕见,只有在__hash__实施不当时才会发生)。

