Converting a list to a set changes element order

后端 未结 11 1099
攒了一身酷
攒了一身酷 2020-11-21 23:26

Recently I noticed that when I am converting a list to set the order of elements is changed and is sorted by character.

Consider this examp

11条回答
  •  长情又很酷
    2020-11-22 00:12

    In mathematics, there are sets and ordered sets (osets).

    • set: an unordered container of unique elements (Implemented)
    • oset: an ordered container of unique elements (NotImplemented)

    In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).

    Given

    a = [1, 2, 20, 6, 210, 2, 1]
    b = {2, 6}
    

    Code

    oset = dict.fromkeys(a).keys()
    # dict_keys([1, 2, 20, 6, 210])
    

    Demo

    Replicates are removed, insertion-order is preserved.

    list(oset)
    # [1, 2, 20, 6, 210]
    

    Set-like operations on dict keys.

    oset - b
    # {1, 20, 210}
    
    oset | b
    # {1, 2, 5, 6, 20, 210}
    
    oset & b
    # {2, 6}
    
    oset ^ b
    # {1, 5, 20, 210}
    

    Details

    Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:

    assert {1, 2, 3} == {2, 3, 1}                    # sets (order is ignored)
    

    assert [1, 2, 3] != [2, 3, 1]                    # lists (order is guaranteed)
    

    One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:

    • list: an ordered container of elements that permits replicates (Implemented)
    • mset: an unordered container of elements that permits replicates (NotImplemented)*

    Summary

    Container | Ordered | Unique | Implemented
    ----------|---------|--------|------------
    set       |    n    |    y   |     y
    oset      |    y    |    y   |     n
    list      |    y    |    n   |     y
    mset      |    n    |    n   |     n*  
    

    *A multiset can be indirectly emulated with collections.Counter(), a dict-like mapping of multiplicities (counts).

提交回复
热议问题