python order of elements in set

2019-01-20 18:52发布

I do not understand the ordering what Python applies from holding sets. For example:

visited = set()
visited.add('C')
visited.add('A')
visited.add('B')
print(set)

The ordering is 'A', 'C', 'B'. Why 'A' is before 'C' (maybe alphabetical order)? What I have to do in order to preserve the adding ordering, i.e. 'C', 'A', 'B'?

标签: python set order
2条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-20 19:19

Sets are different than lists. If you want to preserve an order, use a list. For example :

a = []
a.append('C')
a.append('A')
a.append('B')
print a # ['C', 'A', 'B']
查看更多
再贱就再见
3楼-- · 2019-01-20 19:31

You cannot have order in sets. and there is no way to tell how Python orders it. Check this answer for alternatives.

查看更多
登录 后发表回答