是否可以保证Python列表的元素保持其插入顺序不变?

问题:是否可以保证Python列表的元素保持其插入顺序不变?

如果我有以下Python代码

>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]

x保证始终是[1,2,3],或者是临时元件的其他排序可能吗?

If I have the following Python code

>>> 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?


回答 0

是的,python列表中元素的顺序是持久的。

Yes, the order of elements in a python list is persistent.


回答 1

简而言之,是的,顺序被保留。总而言之:

通常,以下定义将始终应用于列表之类的对象:

一个列表是一个可以包含重复的元素,并具有已定义的顺序通常不会改变,除非明确做这样的元素的集合。堆栈队列都是列表的两种类型,它们为添加和删除元素提供了特定的(通常是有限的)行为(堆栈为LIFO,队列为FIFO)。列表是事物列表的实际表示。可以将字符串视为字符列表,因为顺序很重要("abc" != "bca"),并且肯定允许字符串内容重复("aaa"可以存在和!= "a")。

是不能包含重复元素的集合,并且具有可以或可以不随时间而改变的非定顺序。集不代表事物列表,而是描述事物的某种选择的程度。集合的内部结构及其元素之间的相对存储方式通常并不意味着传达有用的信息。在某些实现中,集合始终在内部进行排序。在其他情况下,顺序只是不确定的(通常取决于哈希函数)。

集合是一个通用术语,指的是用于存储(通常是可变的)许多其他对象的任何对象。列表和集合都是集合的一种。元组和数组通常不被视为集合。某些语言也将地图(描述不同对象之间的关联的容器)也视为一种集合。

这种命名方案适用于我所知道的所有编程语言,包括Python,C ++,Java,C#和Lisp(在这些语言中,如果不按顺序排列将造成严重的灾难性后果)。如果有人知道不是这种情况,请这样说,我将编辑我的答案。请注意,特定的实现可以为这些对象使用其他名称,例如C ++中的vector和ALGOL 68中的flex(两个列表;从技术上讲flex仅是可调整大小的数组)。

如果由于+符号在这里的工作原理而导致您的情况有任何混乱,请只知道顺序对于列表很重要,除非有很好的理由相信否则您可以非常安全地假设列表操作可以保持顺序。在这种情况下,+符号的行为与字符串(反正实际上只是字符列表)的行为非常相似:它将一个列表的内容放置在另一个列表的后面。

如果我们有

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

然后

list1 + list2

是相同的

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

哪个评估

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

很像

"abdcde" + "fghijk"

产生

"abdcdefghijk"

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). 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").

A set is 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 extent of 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).

Collection is 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 vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for 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"

回答 2

您会混淆“集合”和“列表”。集合不能保证顺序,但列表可以保证顺序。

集使用大括号声明:{}。相反,列表使用方括号声明:[]

mySet = {a, b, c, c}

不保证订购,但列表可以:

myList = [a, b, c]

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]

回答 3

我想可能与您有关的一件事是条目是否可以更改,例如,使2变为不同的数字。您可以在这里放心,因为在Python中,整数是不可变的,这意味着它们在创建后就无法更改。

但是,并非Python中的所有内容都是一成不变的。例如,列表是可变的-创建后,列表可以更改。例如,如果您有一个列表列表

>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]

在这里,我更改了a(添加7到)的第一个条目。可以想象一下,如果您不小心,就会在周围乱洗一些东西,并在这里得到意想不到的东西(确实,每个人以某种方式开始用Python编程时,都会发生这种情况;只需在此站点中搜索“在循环浏览时修改列表”它”,以查看数十个示例)。

值得指出的是x = x + [a]x.append(a)它们也不是同一回事。第二个变量突变x,第一个变量创建一个新列表并将其分配给x。要了解差异,请尝试y = x在添加任何内容之前先进行设置,x然后尝试每一项,然后查看两者的差异y

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.

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

>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]

Here, I changed the first entry of a (I added 7 to 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).

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 = x before adding anything to x and trying each one, and look at the difference the two make to y.


回答 4

aList = [1,2,3]

i = 0

for item in aList:  

    if i<2:  

            aList.remove(item)  

    i+=1  

一个列表

[2]

道德是在列表驱动的循环中修改列表时,分两个步骤:

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]

aList=[1,2,3]

i=0

for item in aList:  

    if i<2:  

            aList.remove(item)  

    i+=1  

aList

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

回答 5

是的,列表和元组总是排序的,而字典不是

Yes lists and tuples are always ordered while dictionaries are not