How is the return value of the set function organized?

纵然是瞬间 提交于 2019-12-19 11:53:23

问题


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 the set function organizes it values output. If we think about this, 3 is the first number and 6 is the second on the list, so should it output [3,6,14] instead?


回答1:


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.




回答2:


@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)


来源:https://stackoverflow.com/questions/13412913/how-is-the-return-value-of-the-set-function-organized

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!