包含HashSet< Integer>在Python中 [英] Contains of HashSet<Integer> in Python

查看:58
本文介绍了包含HashSet< Integer>在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们具有 HashSet< Integer> ,我需要在Python中使用类似的结构来使用包含以下内容的内容:

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

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

可以吗?

推荐答案

只需使用一组:

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

列表的相同功能:

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

编辑:
请注意@bholagabbar在下面的评论,其中 in 检查列表和元组的时间复杂度平均为O(n)(请参阅python文档此处),而对于集合,它的平均值为O(1)(最坏的情况也为O(n),但非常罕见,可能仅如果 __ hash __ 的实施不当,就会发生这种情况。

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).

这篇关于包含HashSet&lt; Integer&gt;在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆