简体   繁体   English

集合中元素的python顺序

[英]python order of elements in set

I do not understand the ordering what Python applies from holding sets.我不明白 Python 从保持集应用的顺序。 For example:例如:

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

The ordering is 'A', 'C', 'B' .顺序是'A', 'C', 'B' Why 'A' is before 'C' (maybe alphabetical order)?为什么“A”在“C”之前(可能是按字母顺序排列)? What I have to do in order to preserve the adding ordering, ie 'C', 'A', 'B' ?我必须做什么才能保留添加顺序,即'C', 'A', 'B'

You cannot have order in sets.你不能有成套订单。 and there is no way to tell how Python orders it.并且无法知道 Python 是如何对其进行排序的。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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