4.1 列表数据类型

  1. “列表”是一个值,包含由多个值构成的序列。术语“**列表值**”指的是列表本身(它作为一个值,可以保存在**变量**中或**传递给函数**,像所有其他值一样),而不是指列表值之内的那些值。
  1. >>> spam = ['cat','bat','rat','elephant']
  2. >>> spam
  3. ['cat', 'bat', 'rat', 'elephant']

🔊 spam变量被赋予一个值:列表值,但列表值本身包含多个值。值[ ]是一个空列表,不包含任何值,类似于空字符串。

4.1.1 用索引取得列表中的单个值

  1. >>> spam = [['cat','bat'],[10,20,30,40,50]] #列表值可以包含其他列表值
  2. >>> spam[0]
  3. ['cat', 'bat']
  4. >>> spam[0][1] #第一个索引表明使用哪个列表值,第二个索引表明该列表值中的值
  5. 'bat'
  6. >>> spam[1][4]
  7. 50

4.1.3 利用切片取得子列表

  1. >>> spam = ['cat','bat','rat','elephant']
  2. >>> spam[0:4] #第一个数是开始索引,第二个数是结束处的索引(注意减一法则)
  3. ['cat', 'bat', 'rat', 'elephant']
  4. >>> spam[1:3]
  5. ['bat', 'rat']
  6. >>> spam[0:-1]
  7. ['cat', 'bat', 'rat']

🔊 切片向上增长,直到第二个索引的值,但不包括它。(注意第二个索引的减一法则)

  1. >>> spam = ['cat','bat','rat','elephant']
  2. >>> spam[:2]
  3. ['cat', 'bat']
  4. >>> spam[1:]
  5. ['bat', 'rat', 'elephant']
  6. >>> spam[:]
  7. ['cat', 'bat', 'rat', 'elephant']

🔊 省略第一个索引相当于索引从0或列表开始处开始,省略第二个索引相当于使用列表的长度,意味着切片直到列表的末尾。

4.2 使用列表

  1. #版本①包含大量重复代码,且猫数量发生改变的话,程序就需要添加更多变量来保存更多的猫
  2. print('Enter the name of cat 1:')
  3. catName1 = input()
  4. print('Enter the name of cat 2:')
  5. catName2 = input()
  6. print('Enter the name of cat 3:')
  7. catName3 = input()
  8. print('Enter the name of cat 4:')
  9. catName4 = input()
  10. print('Enter the name of cat 5:')
  11. catName5 = input()
  12. print('Enter the name of cat 6:')
  13. catName6 = input()
  14. print('The cat names are:')
  15. print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' + catName6)
  1. #版本②作为改进版,使用一个空列表用于储存用户输入的任意数量多的猫
  2. catNames = []
  3. while True:
  4. name = input("Enter the name of cat" + str(len(catNames) + 1)
  5. + ("Or enter nothing to stop :"))
  6. if name == '':
  7. break
  8. catNames += [name] # list concatenation
  9. print('The cat names are:')
  10. for name in catNames:
  11. print(' ' + name)

4.2.1 列表用于循环

  1. 循环时针对一个列表或列表中的每个值,重复地执行代码块。
  1. for i in range(4):
  2. print (i)
  3. #↕
  4. for i in [0,1,2,3]:
  5. print (i)

🔊 range(4)返回值是类似于列表的值,Python认为它类似于[0,1,2,3]。(前面的for循环是在执行它的子句,每次迭代中,依次将变量i设为列表中的值)

  1. >>> supplies = ['pens','staplers','flame-throwers','binders']
  2. >>> for i in range(len(supplies)): #由于使用len每次迭代列表 i += 1
  3. print (f"Index {i} in supplies is: {supplies[i]}") #通过列表名 + [i]索引号 每次循环迭代+1
  4. Index 0 in supplies is: pens
  5. Index 1 in supplies is: staplers
  6. Index 2 in supplies is: flame-throwers
  7. Index 3 in supplies is: binders

🔊 循环中的代码可以访问索引(通过变量i),以及索引处的值(通过supplies[i])。range(len(supplies))将迭代所有的的索引,无论包含多少表项。

4.2.2 in和not in 操作符

  1. >>> 'howdy' in ['hello','hi','howdy','heyas']
  2. True
  3. >>> spam = ['hello','hi','howdy','heyas']
  4. >>> 'cat' in spam
  5. False
  6. >>> 'howdy' not in spam
  7. False
  8. >>> 'cat' not in spam
  9. True
  1. myPets = ['Zophie', 'Pooka', 'Fat-tail']
  2. name = input("Enter a pet name:")
  3. if name not in myPets:
  4. print(f"I do not have a pet named {name}")
  5. else:
  6. print(f"{name} is my pet.")

🔊 像其他操作符一样,in和not in 在表达式中用于连接两个值:一个是要在列表中查找的值,另一个是待查找的列表。

4.2.3 多重赋值技巧

  1. 写法①:繁琐
  2. >>> cat = ['fat','black','loud']
  3. >>> size = cat[0]
  4. >>> color = cat[1]
  5. >>> disposition = cat[-1]
  6. #写法②:简略、注意变量的数目和列表的长度必须严格相等。
  7. >>> cat = ['fat','black','loud']
  8. >>> sizi,color,disposition = cat

🔊 多重赋值技巧是一种快捷方式,让你在一行代码中,用列表中的值为多个变量赋值

4.2.4 enumerate()函数与列表一起使用

  1. supplies = ['pens','staplers','flame-throwers','binders']
  2. for index,item in enumerate(supplies): #函数返回对应的索引号与索引到的值(类似于之前的在字典中返回键值对)
  3. print (f"Index {index} in supplies is : {item}")
  4. #Index 0 in supplies is : pens
  5. #Index 1 in supplies is : staplers
  6. #Index 2 in supplies is : flame-throwers
  7. #Index 3 in supplies is : binders

🔊 如果不使用range(len(supplies))技术来获取列表中各表项的整数索引,可用enumerate()函数将返回两个值,列表中表项的索引和列表中的表项本身。

4.2.5 random.choice()和random.shuffle()函数与列表一起使用

  1. >>> import random
  2. >>> pets = ['Dog','Cat',',Moose']
  3. >>> random.choice(pets)
  4. 'Dog'
  5. >>> random.choice(pets)
  6. 'Dog'
  7. >>> random.choice(pets)
  8. 'Cat'
  1. >>> import random
  2. >>> people = ['Alice','Bob','Carol','David']
  3. >>> random.shuffle(people)
  4. >>> people
  5. ['Bob', 'David', 'Alice', 'Carol']

🔊 函数random.choice()将从列表中随机返回一个元素 | random.shuffle()将对列表中的元素重新排序。(永久性修改)

4.3 增强的赋值操作


增强的赋值操作符

增强的赋值语句 等价的赋值语句
spam += 1 spam = spam +1
spam -= 1 spam = spam -1
spam *= 1 spam = spam *1
spam /=1 spam = spam / 1
spam %= 1 spam = spam % 1
  1. >>> spam = 'Hello,'
  2. >>> spam += 'world!'
  3. >>> spam
  4. 'Hello,world!'
  5. >>> bacon = ['Zophie']
  6. >>> bacon *= 3
  7. >>> bacon
  8. ['Zophie', 'Zophie', 'Zophie']

🔊 += 操作符可以完成字符串和列表的拼接 | *= 操作符可以完成字符串和列表的复制


4.4.1 用index()方法在列表中查找值

  1. >>> spam = ['hello','hi','howdy','heyas']
  2. >>> spam.index('hello')
  3. 0
  4. >>> spam.index('heyas')
  5. 3
  6. >>> spam.index('howdy howdy howdy')
  7. Traceback (most recent call last):
  8. File "<pyshell#10>", line 1, in <module>
  9. spam.index('howdy howdy howdy')
  10. ValueError: 'howdy howdy howdy' is not in list

🔊 方法index(),可以传入一个值,如果该值存在于列表中,就返回它的索引号,反之不存在则报错ValueError的错误。

4.4.2 用append()方法和insert()方法在列表中添加值

  1. >>> spam = ['cat','dog','bat'] #append()方法
  2. >>> spam.append('moose')
  3. >>> spam
  4. ['cat', 'dog', 'bat', 'moose']
  5. >>> spam = ['cat','dog','bat'] #insert()方法
  6. >>> spam.insert(1,'chicken')
  7. >>> spam
  8. ['cat', 'chicken', 'dog', 'bat', 'moose']

🔊 append()方法可将参数添加到列表末尾 | insert()方法可以在列表任意索引处插入一个值。(两种方法的返回值为None)

4.4.3 用remove()方法从列表中删除值

  1. >>> spam = ['cat','bat','rat','elephant']
  2. >>> spam.remove('bat')
  3. >>> spam
  4. ['cat', 'rat', 'elephant']

🔊 给remove()方法传入一个值,它可以将该值从列表中删除 | 如果该值在列表中出现多次,只有出现的第一个值会被删除。

4.4.4 用sort方法将列表中的值排序

  1. >>> spam = [2, 5, 3.14, 1, -7] #从小到大的顺序排列
  2. >>> spam.sort()
  3. >>> spam
  4. [-7, 1, 2, 3.14, 5]
  5. >>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] #安字母顺序排列
  6. >>> spam.sort()
  7. >>> spam
  8. ['ants', 'badgers', 'cats', 'dogs', 'elephants']
  9. >>> spam .sort(reverse = True) #在sort()方法中指定reverse关键字参数为True实现sort()方法按逆顺序排序
  10. >>> spam
  11. ['elephants', 'dogs', 'cats', 'badgers', 'ants']

🔊 包含数值的列表或字符串的列表,能用sort()方法排序。| 不能对既有数字又有字符串值的列表进行排序。| 大写字母排在小写字母之前。

4.4.5 使用reverse()方法反转列表中的值

  1. >>> spam = ['cat','dog','moose']
  2. >>> spam.reverse() # 快速反转列表中项目的顺序
  3. >>> spam
  4. ['moose', 'dog', 'cat']

🔊 和sort()方法一样,reverse()方法也不返回列表。注:reverse方法是直接将列表进行反转。

4.5 例子程序:神奇8球和列表

  1. import random
  2. messages = ['It is certain',
  3. 'It is decidedly so',
  4. 'Yes definitely',
  5. 'Reply hazy try again',
  6. 'Ask again later',
  7. 'Concentrate and ask again',
  8. 'My reply is no',
  9. 'Outlook not so good',
  10. 'Very doubtful']
  11. #本质是让messages列表使用randint方法,根据len函数获取的列表长度范围值作为终止点,随机生成的数作为索引号获取值。
  12. print (messages[random.randint(0,len(messages) - 1)])

🔊 -1 是因为len函数会输出真实的列表长度,而获取索引值时遵循减一法则,而len函数输出的末尾值在列表索引中是不存在的,访问到该值会报错!

4.6 序列数据类型

  1. >>> name = 'Zophie'
  2. >>> name[0]
  3. 'Z'
  4. >>> name[-2]
  5. 'i'
  6. >>> name[0:4]
  7. 'Zoph'
  8. >>> 'Zo' in name
  9. True
  10. >>> 'z' in name
  11. False
  12. >>> 'p' not in name
  13. False
  14. >>> for i in name:
  15. print ('***' + i + '***')
  16. ***Z***
  17. ***o***
  18. ***p***
  19. ***h***
  20. ***i***
  21. ***e***

🔊 列表并不是唯一表示序列值的数据类型。| Python序列值包括列表、字符串、由range()返回的范围对象,以及元组。
🔊 对列表的许多操作,也可以用作于字符串和序列类型的其他值:索引取值、切片、用于for循环、用于len()函数,以及用于in和not in 操作符。

4.6.1 可变和不可变数据类型

列表和字符串在一个重要的方面是不同的。列表是“可变”数据类型,它的值可以增、删或改。但是,字符串是“不可变”数据类型,它不能更改。

  1. >>> name = 'Zophie a cat'
  2. >>> name[7] = 'the'
  3. Traceback (most recent call last):
  4. File "<pyshell#11>", line 1, in <module>
  5. name[7] = 'the'
  6. TypeError: 'str' object does not support item assignment
  1. >>> name = 'Zophie a cat'
  2. >>> newName = name[0:7] + 'the' + name[8:12]
  3. >>> name
  4. 'Zophie a cat'
  5. >>> newName
  6. 'Zophie the cat'

🔊 “改变”一个字符串的正确方式,是使用切片和连接构造一个“新的”字符串,从老的字符串那里复制一部分。

  1. >>> eggs = [1,2,3] # 覆写老列表值
  2. >>> eggs = [4,5,6]
  3. >>> eggs
  4. [4, 5, 6]
  5. >>> eggs = [1, 2, 3] # 只有列表被改动,并没有覆写列表值
  6. >>> del eggs[2]
  7. >>> del eggs[1]
  8. >>> del eggs[0]
  9. >>> eggs.append(4)
  10. >>> eggs.append(5)
  11. >>> eggs.append(6)
  12. >>> eggs
  13. [4, 5, 6]

🔊 这种情况,eggs最后的列表值与开始的列表值是一样的。只是这个列表被改变了,而不是被覆写了。

4.6.2 元组数据类型

  1. >>> eggs = ('hello',42,0.5) # 元组不可被增、添、改
  2. >>> eggs[0]
  3. 'hello'
  4. >>> eggs[1:3]
  5. (42, 0.5)
  6. >>> len(eggs)
  7. 3
  8. >>> type(('hello',)) # 在括号内加逗号和不加逗号的区别
  9. <class 'tuple'>
  10. >>> type(('hello'))
  11. <class 'str'>

🔊 元组像字符串一样,是不可变的。| 如果元组只有一个值,你可以在括号内该值得后面跟一个逗号,表明这是一个元组,不然Python会误认。

4.63 用list()和tuple()函数来转换类型

  1. >>> tuple(['cat','dog','5']) # 返回传递给tuple()的值 将其转换为元组类型
  2. ('cat', 'dog', '5')
  3. >>> list(('cat','dog','5'))
  4. ['cat', 'dog', '5']
  5. >>> list(('hello')) # 返回传递给list()的值 将其转换为列表形式
  6. ['h', 'e', 'l', 'l', 'o']
  7. >>> list('hello',)
  8. ['h', 'e', 'l', 'l', 'o']

🔊 函数list()和tuple()将返回传递给它们的值的列表和元组形式。

4.7 引用

正如你所看到的。变量“保存”字符串和整型数。从技术上来说,变量储存的是对计算机内存位置的引用,这些位置存储了这些值。

  1. >>> spam = 42
  2. >>> cheese = spam
  3. >>> spam = 100
  4. >>> spam
  5. 100
  6. >>> cheese #
  7. 42

🔊 将42赋给变量spam时,实际是在计算机内存中创建值42,并对它的“引用”存储在spam变量中,将spam的值更改为100时,你创建了一个新的值100,并将它的引用存储在spam变量中。当你复制spam变量中的值并赋给cheese变量时,实际在复制引用,这不会影响cheese的值,整数是“不变的”值,它们不会改变;更改spam变量实际上是让它引用内存中一个完全不同的值。| 列表不是这样的,因为列表值可以改变。也就是说列表是“可变的”。↓

  1. >>> spam = list(range(0,6))
  2. >>> cheese = spam
  3. >>> cheese[1] = 'Hello'
  4. >>> spam
  5. [0, 'Hello', 2, 3, 4, 5]
  6. >>> cheese
  7. [0, 'Hello', 2, 3, 4, 5]
  1. 这可能让你感到奇怪。代码只改变了cheese 列表,但似乎cheese 和spam 列表同时发生了改变。
  2. 当创建列表时,你将对它的引用赋给了变量spam。但下一行只是将spam 变量中的列表引用复制到cheese变量,而不是列表值本身。这意味着存储在spam 和cheese 中的值,现在指向了同一个列表。底下只有一个列表,因为列表本身实际从未复制。所以当你修改cheese 变量的第一个元素时,也修改了spam 指向的同一个列表。记住,变量就像包含着值的盒子。本章前面的图显示列表在盒子中,这并不准确,因为列表变量实际上没有包含列表,而是包含了对列表的“引用”(这些引用包含一些ID 数字,Python 在内部使用这些ID,但是你可以忽略)。利用盒子作为变量的隐喻。图4-4 展示了列表被赋给spam 变量时发生的情形。

图4-4 spam = [0, 1, 2, 3, 4, 5]保存了对列表的引用,而非实际列表
4章-列表 - 图1

  1. 然后,在图4-5 中,spam 中的引用被复制给cheese。只有新的引用被创建保存在cheese 中,而非新的列表。请注意,两个引用都指向同一个列表。

图4-5 spam = cheese 复制了引用,而非列表
4章-列表 - 图2

  1. 当你改变cheese 指向的列表时,spam 指向的列表也发生了改变,因为cheese和spam 都指向同一个列表,如图4-6 所示。

图4-6 cheese[1] = ‘Hello!’修改了两个变量指向的列表
4章-列表 - 图3
🔊 虽然Python变量在技术上包含的是对值的引用,但人们通常说,该变量包含了该值。

4.7.1 标识和id()函数

  1. >>> id('Howdy') # 它在内存中创建了'Howdy'字符串,id()函数返回储存字符串的数字内存地址
  2. 1929349350960

🔊 Python中的所有值都有一个唯一的标识,可以通过id()函数获得该标识。

  1. >>> bacon = 'Hello' #内存中创建字符串
  2. >>> id(bacon) # 返回字符串的数字内存地址
  3. 1929353569584
  4. >>> bacon += ' World!'
  5. >>> id(bacon) # 修改字符串后 会在内存其他位置创建对象 所有地址发生改变
  6. 1929348654448

🔊 如果“更改”变量中的字符串,就会在内存中的其他位置创建新的字符串对象,并将该变量引用这个新字符串。

  1. >>> eggs = ['cat','dog']
  2. >>> id(eggs) #查看新创建列表的标识
  3. 1779365262720
  4. >>> eggs.append('moose') # 在列表中新添加元素
  5. >>> id(eggs) # 查看列表标识并未发生改变
  6. 1779365262720
  7. >>> eggs = ['bat','rat','cow'] #新创建列表并覆盖掉老列表值
  8. >>> id(eggs) # 标识发生改变
  9. 1779372606208

🔊 两变量引用同一列表,并且列表值如果发生了改变,那么两个变量都会受到影响。(可以修改列表,因为它们是可变对象)

4.7.2 传递引用

  1. def eggs(someParameter): # 2.变元得到的是引用的复制
  2. someParameter.append('Hello')
  3. spam = [1,2,3]
  4. eggs(spam) # 1.调用函数,列表值的列表被复制给变元
  5. print (spam) # [1,2,3,'Hello']
  6. #例 ↓
  7. def eggs(someParameter):
  8. someParameter.append('Hello')
  9. print (id(someParameter))
  10. spam = [1,2,3]
  11. print (id(spam))
  12. eggs(spam)
  13. print (spam)
  14. #3189181328512
  15. #3189181328512
  16. #[1, 2, 3, 'Hello']

🔊 当函数被调用时,参数的值被复制给变元,这意味着变元得到的是引用的复制。| 两个变量虽然包含不同的引用,但它们都指向相同的列表。

4.7.3 copy()模块的copy()和deepcopy()函数

  1. >>> import copy
  2. >>> spam = ['A','B','C','D']
  3. >>> id(spam)
  4. 2150072844480
  5. >>> cheese = copy.copy(spam) #复制列表,不复制引用
  6. >>> id(cheese)
  7. 2150072845952
  8. >>> cheese[1] = 42 # 尝试修改列表后,另一个列表并没有受到影响,因为两个变量都指向独立的列表
  9. >>> spam
  10. ['A', 'B', 'C', 'D']
  11. >>> cheese
  12. ['A', 42, 'C', 'D']

🔊 copy.copy()函数可以用来复制列表或字典这样的可变值,而不只是复制引用。
图4-7 cheese = copy.copy(spam)创建了第二个列表,能独立于第一个列表修改
4章-列表 - 图4
🔊 如果要复制的列表中包含了列表,那就使用copy.deepcopy()函数来代替。deepcopy()函数将同时复制它们内部的列表。(列表里嵌套的列表)

4.8 小程序 Conway的生命游戏

  1. # 康威的生命游戏
  2. import random, time, copy
  3. WIDTH = 60
  4. HEIGHT = 20
  5. # 为单元格创建一个列表。
  6. nextCells = []
  7. for x in range(WIDTH):
  8. column = [] # 创建一个新的列.
  9. for y in range(HEIGHT):
  10. if random.randint(0, 1) == 0:
  11. column.append('#') # 添加一个活细胞.
  12. else:
  13. column.append(' ') # 添加一个死细胞.
  14. nextCells.append(column) # nextCells是一个列的列表.
  15. while True: # 主程序循环.
  16. print('\n\n\n\n\n') # 用换行符分隔每个步骤.
  17. currentCells = copy.deepcopy(nextCells)
  18. # 在屏幕上打印currentCells:
  19. for y in range(HEIGHT):
  20. for x in range(WIDTH):
  21. print(currentCells[x][y], end='') # 打印#或空格.
  22. print() # 在行末打印一个换行符.
  23. # 根据当前步骤的单元格,计算下一步骤的单元格:
  24. for x in range(WIDTH):
  25. for y in range(HEIGHT):
  26. # 获取邻近的坐标:
  27. # `% WIDTH`确保leftCoord总是在0和WIDTH-1之间。
  28. leftCoord = (x - 1) % WIDTH
  29. rightCoord = (x + 1) % WIDTH
  30. aboveCoord = (y - 1) % HEIGHT
  31. belowCoord = (y + 1) % HEIGHT
  32. # 计算活着的邻居的数量:
  33. numNeighbors = 0
  34. if currentCells[leftCoord][aboveCoord] == '#':
  35. numNeighbors += 1 # 左上角的邻居是活的.
  36. if currentCells[x][aboveCoord] == '#':
  37. numNeighbors += 1 # 顶级邻居还活着.
  38. if currentCells[rightCoord][aboveCoord] == '#':
  39. numNeighbors += 1 # 右上角的邻居是活的.
  40. if currentCells[leftCoord][y] == '#':
  41. numNeighbors += 1 # 左边的邻居还活着.
  42. if currentCells[rightCoord][y] == '#':
  43. numNeighbors += 1 # 右边的邻居还活着.
  44. if currentCells[leftCoord][belowCoord] == '#':
  45. numNeighbors += 1 # 左下角的邻居是活的.
  46. if currentCells[x][belowCoord] == '#':
  47. numNeighbors += 1 # 底层邻居还活着.
  48. if currentCells[rightCoord][belowCoord] == '#':
  49. numNeighbors += 1 # 右下角的邻居是活的.
  50. # 基于康威生命游戏规则的设定细胞:
  51. if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
  52. # 有2或3个邻居的活细胞保持活力:
  53. nextCells[x][y] = '#'
  54. elif currentCells[x][y] == ' ' and numNeighbors == 3:
  55. # 有3个邻居的死细胞变成活的:
  56. nextCells[x][y] = '#'
  57. else:
  58. # 其他的东西都会死亡或保持死亡:
  59. nextCells[x][y] = ' '
  60. time.sleep(1) # 增加1秒的停顿,以减少闪动.

4.11.1 逗号代码

  1. def eggs(value):
  2. lists = ''
  3. for a in range(len(value) - 1):
  4. lists += str(value[a]) + ', '
  5. lists += 'and ' + str(value[-1])
  6. return lists
  7. spam=['apple','bananas','tofu','cats']
  8. print (eggs(spam))

4.11.2 掷硬币的连胜