What are the pythonic way to replace a specific set element?

前端 未结 1 1135
我在风中等你
我在风中等你 2021-02-19 12:41

I have a python set set([1, 2, 3]) and always want to replace the third element of the set with another value.

It can be done like below:

def change_last         


        
1条回答
  •  野性不改
    2021-02-19 13:30

    Sets are unordered, so the 'third' element doesn't really mean anything. This will remove an arbitrary element.

    If that is what you want to do, you can simply do:

    data.pop()
    data.add(new_value)
    

    If you wish to remove an item from the set by value and replace it, you can do:

    data.remove(value) #data.discard(value) if you don't care if the item exists.
    data.add(new_value)
    

    If you want to keep ordered data, use a list and do:

    data[index] = new_value
    

    To show that sets are not ordered:

    >>> list({"dog", "cat", "elephant"})
    ['elephant', 'dog', 'cat']
    >>> list({1, 2, 3})
    [1, 2, 3]
    

    You can see that it is only a coincidence of CPython's implementation that '3' is the third element of a list made from the set {1, 2, 3}.

    Your example code is also deeply flawed in other ways. new_list doesn't exist. At no point is the old element removed from the list, and the act of looping through the list is entirely pointless. Obviously, none of that really matters as the whole concept is flawed.

    0 讨论(0)
提交回复
热议问题