简体   繁体   中英

python order of elements in set

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, ie 'C', 'A', 'B' ?

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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM