Preferred Python way of getting the item of a set with a length(/cardinality) of one without removing it?

StackOverflow https://stackoverflow.com/questions/6091922

문제

Given set s, which of the segments below looks better?

if len(s) == 1:
    v = s.copy().pop()
    # important stuff using variable v takes place here

or

if len(s) == 1:
    v = s.pop()
    s.add(v)
    # important stuff using variable v takes place here

or

if len(s) == 1:
    for v in s:
        # important stuff using variable v takes place here

I guess the last segment is the most efficient, but doesn't it look silly to use a loop that never actually loops?

Why don't python sets have an alternative method to pop that doesn't remove the item?

This may seem like a trivial question, but as I've run into this scenario multiple times it has become an itch in need of scratching!

도움이 되었습니까?

해결책

You can assign the only element to v like this:

(v,) = the_set

It raises a exception if the_set doesn't contain exactly one item.

다른 팁

Why don't python sets have an alternative method to pop that doesn't remove the item?

If you want to access the first (and only) item without changing the set structure, use an iterator:

v = iter(s).next()

This works prior to Python 3. In Python 3, you need to use the built-in next function:

v = next(iter(s))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top