且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从集合中检索元素而不删除它?

更新时间:2023-02-14 09:23:48

两个不需要全部复制的选项:

for e in s:休息# e 现在是 s 中的一个元素

或者...

e = next(iter(s))

但总的来说,集合不支持索引或切片.

Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

>>> elem = s.pop()
>>> s.add(elem)

But do you know of a better way? Ideally in constant time.

Two options that don't require copying the whole set:

for e in s:
    break
# e is now an element from s

Or...

e = next(iter(s))

But in general, sets don't support indexing or slicing.