How is the return value of the set function organized?

前端 未结 2 1800
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    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)
    

提交回复
热议问题