Access the sole element of a set

前端 未结 6 695
Happy的楠姐
Happy的楠姐 2020-12-01 23:13

I have a set in 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 elemen

6条回答
  •  抹茶落季
    2020-12-02 00:04

    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).

    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.

提交回复
热议问题