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