[英]converting a set() to an int python
So my question is how can you (or if it can be done at all) convert data type of set to an integer?所以我的问题是你怎么能(或者如果它可以做到)将数据类型的集合转换为 integer?
for example: (IS A TOY EXAMPLE TO EXPLAIN WHAT I'M TRYING TO DO)例如:(是一个玩具示例来解释我正在尝试做的事情)
A = [1, 2, 6, 4, 3]
a_set = set(A)
a_int = a_function(a_set)
print(type(a_int))
Output: <class 'int'>
Output:
<class 'int'>
So any assistance in the conversion of a set() to an int would be greatful.因此,将 set() 转换为 int 的任何帮助都会非常有用。 I have seen this how-can-i-convert-a-set-of-numeric-strings-to-a-set-of-integers which I thought may help but no luck.
我已经看到了这个how-can-i-convert-a-set-of-numeric-strings-to-a-set-of-integers ,我认为这可能会有所帮助,但没有运气。 So thanks in advance.
所以提前谢谢。
What I'm actually trying to do is that I want to return a set that has only one element inside it but I want to return it as an int.我实际上想要做的是我想返回一个里面只有一个元素的集合,但我想把它作为一个 int 返回。
You are not trying to covert a set
to an int
.您不是试图将
set
转换为int
。 You are merely trying to "pull" out the content of the set.您只是试图“拉出”集合的内容。
If you are certain the set contains only one element, you can use .pop
:如果您确定该集合仅包含一个元素,则可以使用
.pop
:
print({1}.pop())
will output将 output
1
If the set contains more than a single element, every call to pop
will grab and return an arbitrary element from it.如果集合包含多个元素,则每次调用
pop
都会从中获取并返回任意元素。
Be careful, if the set is empty calling pop
on it will raise a keyError
exception.请注意,如果 set 为空,则调用
pop
会引发keyError
异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.