How is the return value of the set function organized?

前端 未结 2 1777
不思量自难忘°
不思量自难忘° 2021-01-17 02:45

Here is my code: i used set() and it return [3, 14, 6]

items = [3, 6, 3, 3, 14]
set(items)
>>> set([3,14,6])

My question is how is

相关标签:
2条回答
  • 2021-01-17 03:24

    @Martijn has given you the reason why, but just a couple more bits that might be useful:

    You can use a dict with value as key and the position from your original list as value:

    d = dict( (val, idx) for idx, val in enumerate(items) )
    # or {val:idx for idx, val in enumerate(items)} in 2.7+
    print d.keys() # unique values: [3, 14, 6]
    print sorted(d) # unique values in order [3, 6, 14]
    print sorted(d, key=d.get) # unique values in original order (based on last occurence of key [6, 3, 14]
    

    And slightly a bit more work to get original order, based on first occurence:

    d = {}
    for idx, val in enumerate(items):
        d.setdefault(val, idx)
    
    0 讨论(0)
  • 2021-01-17 03:32

    Sets are unordered. From the documentation:

    Being an unordered collection, sets do not record element position or order of insertion.

    Like dictionaries, the ordering is based on the hashes of the stored keys. You cannot rely on this apparent ordering to remain stable.

    If you are interested in the underlying data model, the underlying data structure is called a Hash Table, but in sets only keys are stored, values are left empty.

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