如果我有以下Python代码
>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]
是否保证x总是[1,2,3],或者是否可能有其他的临时元素顺序?
如果我有以下Python代码
>>> x = []
>>> x = x + [1]
>>> x = x + [2]
>>> x = x + [3]
>>> x
[1, 2, 3]
是否保证x总是[1,2,3],或者是否可能有其他的临时元素顺序?
简而言之,是的,秩序得以保留。长:
一般来说,下面的定义总是适用于像列表这样的对象:
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).
集合是一个通用术语,指用于存储(通常是可变数量的)其他对象的任何对象。列表和集合都是一种集合。元组和数组通常不被认为是集合。有些语言认为map(描述不同对象之间关联的容器)也是一种类型的集合。
这种命名模式适用于我所知道的所有编程语言,包括Python、c++、Java、c#和Lisp(在Lisp中,列表不按顺序排列将是灾难性的)。如果有人知道哪里不是这样的,请直接说出来,我会编辑我的答案。注意,特定的实现可能会为这些对象使用其他名称,例如c++中的vector和ALGOL 68中的flex(两者都列出了;Flex技术上只是一个可调整大小的数组)。
如果您对这里的+号的具体工作方式有任何困惑,只要知道顺序对列表很重要就可以了,除非有很好的理由相信不这样做,否则您几乎总是可以安全地假设列表操作保持顺序。在这种情况下,+号的行为很像字符串(实际上只是字符列表):它取一个列表的内容,并将其放在另一个列表的内容后面。
如果我们有
list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]
Then
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"
我想你们可能关心的一件事是这些元素是否会改变,比如,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。要看区别,在向x添加任何东西之前尝试设置y = x,并尝试每一个,看看两者对y的影响。
列表=[1,2,3]
我= 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]
你把“集合”和“列表”搞混了。集合不能保证顺序,但是列表可以。
集合使用花括号:{}声明。相反,列表使用方括号:[]声明。
mySet = {a, b, c, c}
不保证顺序,但列表做到:
myList = [a, b, c]