本文翻译自:Is a Python list guaranteed to have its elements stay in the order they are inserted in?
If I have the following Python code 如果我有以下Python代码
>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]
Will x
be guaranteed to always be [1,2,3]
, or are other orderings of the interim elements possible? x
将保证始终为[1,2,3]
,还是可能的其他临时元素排序?
#1楼
参考:https://stackoom.com/question/vSRW/是否保证Python列表的元素保持按插入顺序排列
#2楼
是的,python列表中元素的顺序是持久的。
#3楼
In short, yes, the order is preserved. 简而言之,是的,订单得以保留。 In long: 长期:
In general the following definitions will always apply to objects like lists: 通常,以下定义将始终适用于列表之类的对象:
A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. 列表是可以包含重复元素的元素的集合,并且具有通常不会更改的已定义顺序,除非明确指示这样做。 stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). 堆栈和队列都是列表类型,它们为添加和删除元素提供特定的(通常是有限的)行为(堆栈为LIF