Python 列表是否保证其元素按插入顺序保持不变?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13694034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is a Python list guaranteed to have its elements stay in the order they are inserted in?
提问by samoz
If I have the following Python code
如果我有以下 Python 代码
>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]
Will xbe guaranteed to always be [1,2,3], or are other orderings of the interim elements possible?
将x保证始终为[1,2,3],还是可以对中间元素进行其他排序?
采纳答案by sge
Yes, the order of elements in a python list is persistent.
是的,python 列表中元素的顺序是持久的。
回答by ApproachingDarknessFish
In short, yes, the order is preserved. In long:
简而言之,是的,订单被保留。长:
In general the following definitions will always apply to objects like lists:
通常,以下定义将始终适用于列表等对象:
A listis 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. stacksand queuesare both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa"can exist and != "a").
一个列表是一个可以包含重复的元素,并具有已定义的顺序通常不会改变,除非明确做这样的元素的集合。堆栈和队列都是列表类型,它们提供用于添加和删除元素的特定(通常是有限的)行为(堆栈是 LIFO,队列是 FIFO)。列表是事物列表的实际表示。一个字符串可以被认为是一个字符列表,因为顺序很重要 ( "abc" != "bca") 并且字符串内容中的重复当然是允许的("aaa"可以存在 和!= "a")。
A setis a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extentof a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).
甲集是不能包含重复元素的集合,并且具有可以或可以不随时间而改变的非定顺序。因为它们所描述的设置并不代表事情列出这么多的程度的事情有一定的选择的。set 的内部结构,它的元素如何相对于彼此存储,通常并不意味着传达有用的信息。在某些实现中,集合总是在内部排序;在其他情况下,排序只是未定义(通常取决于散列函数)。
Collectionis a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps(containers that describe associations between different objects) to be a type of collection as well.
集合是一个通用术语,指的是用于存储(通常是可变的)数量的其他对象的任何对象。列表和集合都是一种集合。元组和数组通常不被视为集合。一些语言也将映射(描述不同对象之间关联的容器)视为一种集合。
This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vectorin C++ and flexin ALGOL 68 (both lists; flex is technically just a re-sizable array).
这种命名方案适用于我所知道的所有编程语言,包括 Python、C++、Java、C# 和 Lisp(在这些语言中,不保持顺序的列表将是特别灾难性的)。如果有人知道情况并非如此,请直接说出来,我会编辑我的答案。请注意,特定实现可能对这些对象使用其他名称,例如C++ 中的vector和ALGOL 68 中的flex(两个列表;flex 在技术上只是一个可重新调整大小的数组)。
If there is any confusion left in your case due to the specifics of how the +sign works here, just know that order is importantfor lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the +sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.
如果由于+符号在这里工作的细节而在您的情况下留下任何混淆,请知道顺序对于列表很重要,除非有很好的理由相信否则您几乎总是可以安全地假设列表操作保留顺序. 在这种情况下,+符号的行为与字符串(无论如何实际上只是字符列表)非常相似:它获取列表的内容并将其放在另一个内容的后面。
If we have
如果我们有
list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]
Then
然后
list1 + list2
Is the same as
是相同的
[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]
Which evaluates to
其中评估为
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Much like
很像
"abdcde" + "fghijk"
Produces
生产
"abdcdefghijk"
回答by asmeurer
I suppose one thing that may be concerning you is whether or not the entries could change, so that the 2 becomes a different number, for instance. You can put your mind at ease here, because in Python, integers are immutable, meaning they cannot change after they are created.
我想可能与您有关的一件事是条目是否可以更改,例如,2 变为不同的数字。在这里您可以放心,因为在 Python 中,整数是不可变的,这意味着它们在创建后无法更改。
Not everything in Python is immutable, though. For example, lists are mutable---they can change after being created. So for example, if you had a list of lists
但是,并非 Python 中的所有内容都是不可变的。例如,列表是可变的——它们可以在创建后更改。例如,如果您有一个列表列表
>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]
Here, I changed the first entry of a(I added 7to it). One could imagine shuffling things around, and getting unexpected things here if you are not careful (and indeed, this does happen to everyone when they start programming in Python in some way or another; just search this site for "modifying a list while looping through it" to see dozens of examples).
在这里,我更改了a(我添加的7)的第一个条目。如果你不小心的话,你可以想象周围的事情发生变化,并在这里得到意想不到的东西(事实上,当他们以某种方式开始用 Python 编程时,这确实发生在每个人身上;只需在此站点中搜索“在循环中修改列表”它”以查看数十个示例)。
It's also worth pointing out that x = x + [a]and x.append(a)are not the same thing. The second one mutates x, and the first one creates a new list and assigns it to x. To see the difference, try setting y = xbefore adding anything to xand trying each one, and look at the difference the two make to y.
还值得指出的是x = x + [a]和x.append(a)不是一回事。第二个发生变化x,第一个创建一个新列表并将其分配给x. 要查看差异,请y = x在添加任何内容之前尝试设置x并尝试每个,然后查看两者对y.
回答by ralphie boy
aList=[1,2,3]
aList=[1,2,3]
i=0
我=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
一个列表
[2]
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
道德是在由列表驱动的循环中修改列表时,需要两个步骤:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
回答by Jonathan Muckell
You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.
你混淆了“集合”和“列表”。集合不能保证顺序,但列表可以。
Sets are declared using curly brackets: {}. In contrast, lists are declared using square brackets: [].
集合使用大括号声明:{}。相反,列表是使用方括号声明的:[]。
mySet = {a, b, c, c}
Does not guarantee order, but list does:
不保证顺序,但列表可以:
myList = [a, b, c]
回答by Ysh
Yes lists and tuples are always ordered while dictionaries are not
是的,列表和元组总是有序的,而字典则不是

