Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

type conversion - 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?

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'>

So any assistance in the conversion of a set() to an int would be greatful. 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. 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.

question from:https://stackoverflow.com/questions/65851341/converting-a-set-to-an-int-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not trying to covert a set to an 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:

print({1}.pop())

will output

1

If the set contains more than a single element, every call to pop will grab and return an arbitrary element from it.

Be careful, if the set is empty calling pop on it will raise a keyError exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...