Python 访问集合的唯一元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20625579/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:51:41  来源:igfitidea点击:

Access the sole element of a set

pythonset

提问by Nik

I have a setin Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that element. How do I access this element from the set?

set在 Python 中有一个,我根据条件从中一个一个地删除元素。当集合只剩下 1 个元素时,我需要返回该元素。我如何从集合中访问这个元素?

A simplified example:

一个简化的例子:

S = set(range(5))
for i in range(4):
    S = S - {i}
# now S has only 1 element: 4
return ? # how should I access this element
# a lame way is the following
# for e in S:
#    return S

采纳答案by Nik

Use set.pop:

使用set.pop

>>> {1}.pop()
1
>>>

In your case, it would be:

在您的情况下,它将是:

return S.pop()


Note however that this will remove the item from the set. If this is undesirable, you can use min|max:

但是请注意,这将从集合中删除该项目。如果这是不可取的,您可以使用min| max

return min(S) # 'max' would also work here

Demo:

演示:

>>> S = {1}
>>> min(S)
1
>>> S
set([1])
>>> max(S)
1
>>> S
set([1])
>>> 

回答by Raymond Hettinger

I would use:

我会用:

e = next(iter(S))

This is non-destructive and works even when there is more than one element in the set. Even better, it has an option to supply a default value e = next(iter(S), default).

这是非破坏性的,即使在集合中有多个元素时也能工作。更好的是,它可以选择提供默认值e = next(iter(S), default)

You could also use unpacking:

您还可以使用解包:

[e] = S

The unpacking technique is likely to be the fastest way and it includes error checking to make sure the set has only one member. The downside is that it looks weird.

解包技术可能是最快的方法,它包括错误检查以确保集合只有一个成员。缺点是看起来很奇怪。

回答by Fatih1923

You can assign the last element to a variable, using star operation.

您可以使用 将最后一个元素分配给变量star operation

>>> a={"fatih"}
>>> b=str(*a)
>>> b
'fatih'

Now the varible bhave a string object.

现在变量b有一个string object.

If the sole elemant is a number, you could use int():

如果唯一的元素是数字,则可以使用int()

>>> a={1}
>>> c=int(*a)
>>> c
1

回答by J4y

Sorry, late to the party. To access an element from a set you can always cast the set into a list and then you can use indexing to return the value you want.

抱歉,聚会迟到了。要访问集合中的元素,您始终可以将集合转换为列表,然后您可以使用索引来返回您想要的值。

In the case of your example:

就您的示例而言:

return list(S)[0]

回答by Jon Nicholson

One way is: value=min(set(['a','b','c'))produces 'a'. Obviously you can use maxinstead.

一种方法是:value=min(set(['a','b','c'))产生'a'. 显然你可以使用max