Access the sole element of a set

前端 未结 6 696
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-01 23:46

    Use set.pop:

    >>> {1}.pop()
    1
    >>>
    

    In your case, it would be:

    return S.pop()
    

    Note however that this will remove the item from the set. If this is undesirable, you can use min|max:

    return min(S) # 'max' would also work here
    

    Demo:

    >>> S = {1}
    >>> min(S)
    1
    >>> S
    set([1])
    >>> max(S)
    1
    >>> S
    set([1])
    >>> 
    
    0 讨论(0)
  • 2020-12-01 23:49
    1. A set is an unordered collection with no duplicate elements.

    2. Basic uses include membership testing and eliminating duplicate entries.

    3. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

    4. to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

    5. sort a set in acceding/Descending order -> Returns a List of sorted elements, doesn't change the set

      sorted(basket) # In Ascending Order sorted(basket, reverse=True) # In descending order

    To get x element of set or from sorted set

    list(basket)[x] or sorted(basket)[x] 
    

    Note: set is unordered set, so you can use the below code to get x element from a sorted set

    0 讨论(0)
  • 2020-12-01 23:52

    You can assign the last element to a variable, using star operation.

    >>> a={"fatih"}
    >>> b=str(*a)
    >>> b
    'fatih'
    

    Now the varible b have a string object.

    If the sole elemant is a number, you could use int():

    >>> a={1}
    >>> c=int(*a)
    >>> c
    1
    
    0 讨论(0)
  • 2020-12-01 23:56

    One way is: value=min(set(['a','b','c')) produces 'a'. Obviously you can use max instead.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 00:10

    Sorry, late to the party. To access an element from a set you can always cast the set into a list and then you can use indexing to return the value you want.

    In the case of your example:

    return list(S)[0]
    
    0 讨论(0)
提交回复
热议问题