How to extract the member from single-member set in python?

前端 未结 6 1294
感动是毒
感动是毒 2020-12-23 18:46

I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this appro

6条回答
  •  暖寄归人
    2020-12-23 19:09

    I reckon kaizer.se's answer is great. But if your set might contain more than one element, and you want a not-so-arbitrary element, you might want to use min or max. E.g.:

    element = min(myset)
    

    or:

    element = max(myset)
    

    (Don't use sorted, because that has unnecessary overhead for this usage.)

提交回复
热议问题