- 4.1 列表数据类型
- 4.1.1 用索引取得列表中的单个值
- 4.1.3 利用切片取得子列表
- 4.2 使用列表
- 4.2.1 列表用于循环
- 4.2.2 in和not in 操作符
- 4.2.3 多重赋值技巧
- 4.2.4 enumerate()函数与列表一起使用
- 4.2.5 random.choice()和random.shuffle()函数与列表一起使用
- 4.3 增强的赋值操作
- 4.4.1 用index()方法在列表中查找值
- 4.4.2 用append()方法和insert()方法在列表中添加值
- 4.4.3 用remove()方法从列表中删除值
- 4.4.4 用sort方法将列表中的值排序
- 4.4.5 使用reverse()方法反转列表中的值
- 4.5 例子程序:神奇8球和列表
- 4.6 序列数据类型
- 4.6.1 可变和不可变数据类型
- 4.6.2 元组数据类型
- 4.63 用list()和tuple()函数来转换类型
- 4.7 引用
- 4.7.1 标识和id()函数
- 4.7.2 传递引用
- 4.7.3 copy()模块的copy()和deepcopy()函数
- 4.8 小程序 Conway的生命游戏
- 4.11.1 逗号代码
- 4.11.2 掷硬币的连胜
4.1 列表数据类型
“列表”是一个值,包含由多个值构成的序列。术语“**列表值**”指的是列表本身(它作为一个值,可以保存在**变量**中或**传递给函数**,像所有其他值一样),而不是指列表值之内的那些值。
>>> spam = ['cat','bat','rat','elephant']>>> spam['cat', 'bat', 'rat', 'elephant']
🔊 spam变量被赋予一个值:列表值,但列表值本身包含多个值。值[ ]是一个空列表,不包含任何值,类似于空字符串。
4.1.1 用索引取得列表中的单个值
>>> spam = [['cat','bat'],[10,20,30,40,50]] #列表值可以包含其他列表值>>> spam[0]['cat', 'bat']>>> spam[0][1] #第一个索引表明使用哪个列表值,第二个索引表明该列表值中的值'bat'>>> spam[1][4]50
4.1.3 利用切片取得子列表
>>> spam = ['cat','bat','rat','elephant']>>> spam[0:4] #第一个数是开始索引,第二个数是结束处的索引(注意减一法则)['cat', 'bat', 'rat', 'elephant']>>> spam[1:3]['bat', 'rat']>>> spam[0:-1]['cat', 'bat', 'rat']
🔊 切片向上增长,直到第二个索引的值,但不包括它。(注意第二个索引的减一法则)
>>> spam = ['cat','bat','rat','elephant']>>> spam[:2]['cat', 'bat']>>> spam[1:]['bat', 'rat', 'elephant']>>> spam[:]['cat', 'bat', 'rat', 'elephant']
🔊 省略第一个索引相当于索引从0或列表开始处开始,省略第二个索引相当于使用列表的长度,意味着切片直到列表的末尾。
4.2 使用列表
#版本①包含大量重复代码,且猫数量发生改变的话,程序就需要添加更多变量来保存更多的猫print('Enter the name of cat 1:')catName1 = input()print('Enter the name of cat 2:')catName2 = input()print('Enter the name of cat 3:')catName3 = input()print('Enter the name of cat 4:')catName4 = input()print('Enter the name of cat 5:')catName5 = input()print('Enter the name of cat 6:')catName6 = input()print('The cat names are:')print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' + catName6)
#版本②作为改进版,使用一个空列表用于储存用户输入的任意数量多的猫catNames = []while True:name = input("Enter the name of cat" + str(len(catNames) + 1)+ ("Or enter nothing to stop :"))if name == '':breakcatNames += [name] # list concatenationprint('The cat names are:')for name in catNames:print(' ' + name)
4.2.1 列表用于循环
循环时针对一个列表或列表中的每个值,重复地执行代码块。
for i in range(4):print (i)#↕for i in [0,1,2,3]:print (i)
🔊 range(4)返回值是类似于列表的值,Python认为它类似于[0,1,2,3]。(前面的for循环是在执行它的子句,每次迭代中,依次将变量i设为列表中的值)
>>> supplies = ['pens','staplers','flame-throwers','binders']>>> for i in range(len(supplies)): #由于使用len每次迭代列表 i += 1print (f"Index {i} in supplies is: {supplies[i]}") #通过列表名 + [i]索引号 每次循环迭代+1Index 0 in supplies is: pensIndex 1 in supplies is: staplersIndex 2 in supplies is: flame-throwersIndex 3 in supplies is: binders
🔊 循环中的代码可以访问索引(通过变量i),以及索引处的值(通过supplies[i])。range(len(supplies))将迭代所有的的索引,无论包含多少表项。
4.2.2 in和not in 操作符
>>> 'howdy' in ['hello','hi','howdy','heyas']True>>> spam = ['hello','hi','howdy','heyas']>>> 'cat' in spamFalse>>> 'howdy' not in spamFalse>>> 'cat' not in spamTrue
myPets = ['Zophie', 'Pooka', 'Fat-tail']name = input("Enter a pet name:")if name not in myPets:print(f"I do not have a pet named {name}")else:print(f"{name} is my pet.")
🔊 像其他操作符一样,in和not in 在表达式中用于连接两个值:一个是要在列表中查找的值,另一个是待查找的列表。
4.2.3 多重赋值技巧
写法①:繁琐>>> cat = ['fat','black','loud']>>> size = cat[0]>>> color = cat[1]>>> disposition = cat[-1]#写法②:简略、注意变量的数目和列表的长度必须严格相等。>>> cat = ['fat','black','loud']>>> sizi,color,disposition = cat
🔊 多重赋值技巧是一种快捷方式,让你在一行代码中,用列表中的值为多个变量赋值
4.2.4 enumerate()函数与列表一起使用
supplies = ['pens','staplers','flame-throwers','binders']for index,item in enumerate(supplies): #函数返回对应的索引号与索引到的值(类似于之前的在字典中返回键值对)print (f"Index {index} in supplies is : {item}")#Index 0 in supplies is : pens#Index 1 in supplies is : staplers#Index 2 in supplies is : flame-throwers#Index 3 in supplies is : binders
🔊 如果不使用range(len(supplies))技术来获取列表中各表项的整数索引,可用enumerate()函数将返回两个值,列表中表项的索引和列表中的表项本身。
4.2.5 random.choice()和random.shuffle()函数与列表一起使用
>>> import random>>> pets = ['Dog','Cat',',Moose']>>> random.choice(pets)'Dog'>>> random.choice(pets)'Dog'>>> random.choice(pets)'Cat'
>>> import random>>> people = ['Alice','Bob','Carol','David']>>> random.shuffle(people)>>> people['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 |
>>> spam = 'Hello,'>>> spam += 'world!'>>> spam'Hello,world!'>>> bacon = ['Zophie']>>> bacon *= 3>>> bacon['Zophie', 'Zophie', 'Zophie']
🔊 += 操作符可以完成字符串和列表的拼接 | *= 操作符可以完成字符串和列表的复制
4.4.1 用index()方法在列表中查找值
>>> spam = ['hello','hi','howdy','heyas']>>> spam.index('hello')0>>> spam.index('heyas')3>>> spam.index('howdy howdy howdy')Traceback (most recent call last):File "<pyshell#10>", line 1, in <module>spam.index('howdy howdy howdy')ValueError: 'howdy howdy howdy' is not in list
🔊 方法index(),可以传入一个值,如果该值存在于列表中,就返回它的索引号,反之不存在则报错ValueError的错误。
4.4.2 用append()方法和insert()方法在列表中添加值
>>> spam = ['cat','dog','bat'] #append()方法>>> spam.append('moose')>>> spam['cat', 'dog', 'bat', 'moose']>>> spam = ['cat','dog','bat'] #insert()方法>>> spam.insert(1,'chicken')>>> spam['cat', 'chicken', 'dog', 'bat', 'moose']
🔊 append()方法可将参数添加到列表末尾 | insert()方法可以在列表任意索引处插入一个值。(两种方法的返回值为None)
4.4.3 用remove()方法从列表中删除值
>>> spam = ['cat','bat','rat','elephant']>>> spam.remove('bat')>>> spam['cat', 'rat', 'elephant']
🔊 给remove()方法传入一个值,它可以将该值从列表中删除 | 如果该值在列表中出现多次,只有出现的第一个值会被删除。
4.4.4 用sort方法将列表中的值排序
>>> spam = [2, 5, 3.14, 1, -7] #从小到大的顺序排列>>> spam.sort()>>> spam[-7, 1, 2, 3.14, 5]>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] #安字母顺序排列>>> spam.sort()>>> spam['ants', 'badgers', 'cats', 'dogs', 'elephants']>>> spam .sort(reverse = True) #在sort()方法中指定reverse关键字参数为True实现sort()方法按逆顺序排序>>> spam['elephants', 'dogs', 'cats', 'badgers', 'ants']
🔊 包含数值的列表或字符串的列表,能用sort()方法排序。| 不能对既有数字又有字符串值的列表进行排序。| 大写字母排在小写字母之前。
4.4.5 使用reverse()方法反转列表中的值
>>> spam = ['cat','dog','moose']>>> spam.reverse() # 快速反转列表中项目的顺序>>> spam['moose', 'dog', 'cat']
🔊 和sort()方法一样,reverse()方法也不返回列表。注:reverse方法是直接将列表进行反转。
4.5 例子程序:神奇8球和列表
import randommessages = ['It is certain','It is decidedly so','Yes definitely','Reply hazy try again','Ask again later','Concentrate and ask again','My reply is no','Outlook not so good','Very doubtful']#本质是让messages列表使用randint方法,根据len函数获取的列表长度范围值作为终止点,随机生成的数作为索引号获取值。print (messages[random.randint(0,len(messages) - 1)])
🔊 -1 是因为len函数会输出真实的列表长度,而获取索引值时遵循减一法则,而len函数输出的末尾值在列表索引中是不存在的,访问到该值会报错!
4.6 序列数据类型
>>> name = 'Zophie'>>> name[0]'Z'>>> name[-2]'i'>>> name[0:4]'Zoph'>>> 'Zo' in nameTrue>>> 'z' in nameFalse>>> 'p' not in nameFalse>>> for i in name:print ('***' + i + '***')***Z******o******p******h******i******e***
🔊 列表并不是唯一表示序列值的数据类型。| Python序列值包括列表、字符串、由range()返回的范围对象,以及元组。
🔊 对列表的许多操作,也可以用作于字符串和序列类型的其他值:索引取值、切片、用于for循环、用于len()函数,以及用于in和not in 操作符。
4.6.1 可变和不可变数据类型
列表和字符串在一个重要的方面是不同的。列表是“可变”数据类型,它的值可以增、删或改。但是,字符串是“不可变”数据类型,它不能更改。
>>> name = 'Zophie a cat'>>> name[7] = 'the'Traceback (most recent call last):File "<pyshell#11>", line 1, in <module>name[7] = 'the'TypeError: 'str' object does not support item assignment
>>> name = 'Zophie a cat'>>> newName = name[0:7] + 'the' + name[8:12]>>> name'Zophie a cat'>>> newName'Zophie the cat'
🔊 “改变”一个字符串的正确方式,是使用切片和连接构造一个“新的”字符串,从老的字符串那里复制一部分。
>>> eggs = [1,2,3] # 覆写老列表值>>> eggs = [4,5,6]>>> eggs[4, 5, 6]>>> eggs = [1, 2, 3] # 只有列表被改动,并没有覆写列表值>>> del eggs[2]>>> del eggs[1]>>> del eggs[0]>>> eggs.append(4)>>> eggs.append(5)>>> eggs.append(6)>>> eggs[4, 5, 6]
🔊 这种情况,eggs最后的列表值与开始的列表值是一样的。只是这个列表被改变了,而不是被覆写了。
4.6.2 元组数据类型
>>> eggs = ('hello',42,0.5) # 元组不可被增、添、改>>> eggs[0]'hello'>>> eggs[1:3](42, 0.5)>>> len(eggs)3>>> type(('hello',)) # 在括号内加逗号和不加逗号的区别<class 'tuple'>>>> type(('hello'))<class 'str'>
🔊 元组像字符串一样,是不可变的。| 如果元组只有一个值,你可以在括号内该值得后面跟一个逗号,表明这是一个元组,不然Python会误认。
4.63 用list()和tuple()函数来转换类型
>>> tuple(['cat','dog','5']) # 返回传递给tuple()的值 将其转换为元组类型('cat', 'dog', '5')>>> list(('cat','dog','5'))['cat', 'dog', '5']>>> list(('hello')) # 返回传递给list()的值 将其转换为列表形式['h', 'e', 'l', 'l', 'o']>>> list('hello',)['h', 'e', 'l', 'l', 'o']
🔊 函数list()和tuple()将返回传递给它们的值的列表和元组形式。
4.7 引用
正如你所看到的。变量“保存”字符串和整型数。从技术上来说,变量储存的是对计算机内存位置的引用,这些位置存储了这些值。
>>> spam = 42>>> cheese = spam>>> spam = 100>>> spam100>>> cheese #42
🔊 将42赋给变量spam时,实际是在计算机内存中创建值42,并对它的“引用”存储在spam变量中,将spam的值更改为100时,你创建了一个新的值100,并将它的引用存储在spam变量中。当你复制spam变量中的值并赋给cheese变量时,实际在复制引用,这不会影响cheese的值,整数是“不变的”值,它们不会改变;更改spam变量实际上是让它引用内存中一个完全不同的值。| 列表不是这样的,因为列表值可以改变。也就是说列表是“可变的”。↓
>>> spam = list(range(0,6))>>> cheese = spam>>> cheese[1] = 'Hello'>>> spam[0, 'Hello', 2, 3, 4, 5]>>> cheese[0, 'Hello', 2, 3, 4, 5]
这可能让你感到奇怪。代码只改变了cheese 列表,但似乎cheese 和spam 列表同时发生了改变。当创建列表时,你将对它的引用赋给了变量spam。但下一行只是将spam 变量中的列表引用复制到cheese变量,而不是列表值本身。这意味着存储在spam 和cheese 中的值,现在指向了同一个列表。底下只有一个列表,因为列表本身实际从未复制。所以当你修改cheese 变量的第一个元素时,也修改了spam 指向的同一个列表。记住,变量就像包含着值的盒子。本章前面的图显示列表在盒子中,这并不准确,因为列表变量实际上没有包含列表,而是包含了对列表的“引用”(这些引用包含一些ID 数字,Python 在内部使用这些ID,但是你可以忽略)。利用盒子作为变量的隐喻。图4-4 展示了列表被赋给spam 变量时发生的情形。
图4-4 spam = [0, 1, 2, 3, 4, 5]保存了对列表的引用,而非实际列表
然后,在图4-5 中,spam 中的引用被复制给cheese。只有新的引用被创建保存在cheese 中,而非新的列表。请注意,两个引用都指向同一个列表。
图4-5 spam = cheese 复制了引用,而非列表
当你改变cheese 指向的列表时,spam 指向的列表也发生了改变,因为cheese和spam 都指向同一个列表,如图4-6 所示。
图4-6 cheese[1] = ‘Hello!’修改了两个变量指向的列表
🔊 虽然Python变量在技术上包含的是对值的引用,但人们通常说,该变量包含了该值。
4.7.1 标识和id()函数
>>> id('Howdy') # 它在内存中创建了'Howdy'字符串,id()函数返回储存字符串的数字内存地址1929349350960
🔊 Python中的所有值都有一个唯一的标识,可以通过id()函数获得该标识。
>>> bacon = 'Hello' #内存中创建字符串>>> id(bacon) # 返回字符串的数字内存地址1929353569584>>> bacon += ' World!'>>> id(bacon) # 修改字符串后 会在内存其他位置创建对象 所有地址发生改变1929348654448
🔊 如果“更改”变量中的字符串,就会在内存中的其他位置创建新的字符串对象,并将该变量引用这个新字符串。
>>> eggs = ['cat','dog']>>> id(eggs) #查看新创建列表的标识1779365262720>>> eggs.append('moose') # 在列表中新添加元素>>> id(eggs) # 查看列表标识并未发生改变1779365262720>>> eggs = ['bat','rat','cow'] #新创建列表并覆盖掉老列表值>>> id(eggs) # 标识发生改变1779372606208
🔊 两变量引用同一列表,并且列表值如果发生了改变,那么两个变量都会受到影响。(可以修改列表,因为它们是可变对象)
4.7.2 传递引用
def eggs(someParameter): # 2.变元得到的是引用的复制someParameter.append('Hello')spam = [1,2,3]eggs(spam) # 1.调用函数,列表值的列表被复制给变元print (spam) # [1,2,3,'Hello']#例 ↓def eggs(someParameter):someParameter.append('Hello')print (id(someParameter))spam = [1,2,3]print (id(spam))eggs(spam)print (spam)#3189181328512#3189181328512#[1, 2, 3, 'Hello']
🔊 当函数被调用时,参数的值被复制给变元,这意味着变元得到的是引用的复制。| 两个变量虽然包含不同的引用,但它们都指向相同的列表。
4.7.3 copy()模块的copy()和deepcopy()函数
>>> import copy>>> spam = ['A','B','C','D']>>> id(spam)2150072844480>>> cheese = copy.copy(spam) #复制列表,不复制引用>>> id(cheese)2150072845952>>> cheese[1] = 42 # 尝试修改列表后,另一个列表并没有受到影响,因为两个变量都指向独立的列表>>> spam['A', 'B', 'C', 'D']>>> cheese['A', 42, 'C', 'D']
🔊 copy.copy()函数可以用来复制列表或字典这样的可变值,而不只是复制引用。
图4-7 cheese = copy.copy(spam)创建了第二个列表,能独立于第一个列表修改
🔊 如果要复制的列表中包含了列表,那就使用copy.deepcopy()函数来代替。deepcopy()函数将同时复制它们内部的列表。(列表里嵌套的列表)
4.8 小程序 Conway的生命游戏
# 康威的生命游戏import random, time, copyWIDTH = 60HEIGHT = 20# 为单元格创建一个列表。nextCells = []for x in range(WIDTH):column = [] # 创建一个新的列.for y in range(HEIGHT):if random.randint(0, 1) == 0:column.append('#') # 添加一个活细胞.else:column.append(' ') # 添加一个死细胞.nextCells.append(column) # nextCells是一个列的列表.while True: # 主程序循环.print('\n\n\n\n\n') # 用换行符分隔每个步骤.currentCells = copy.deepcopy(nextCells)# 在屏幕上打印currentCells:for y in range(HEIGHT):for x in range(WIDTH):print(currentCells[x][y], end='') # 打印#或空格.print() # 在行末打印一个换行符.# 根据当前步骤的单元格,计算下一步骤的单元格:for x in range(WIDTH):for y in range(HEIGHT):# 获取邻近的坐标:# `% WIDTH`确保leftCoord总是在0和WIDTH-1之间。leftCoord = (x - 1) % WIDTHrightCoord = (x + 1) % WIDTHaboveCoord = (y - 1) % HEIGHTbelowCoord = (y + 1) % HEIGHT# 计算活着的邻居的数量:numNeighbors = 0if currentCells[leftCoord][aboveCoord] == '#':numNeighbors += 1 # 左上角的邻居是活的.if currentCells[x][aboveCoord] == '#':numNeighbors += 1 # 顶级邻居还活着.if currentCells[rightCoord][aboveCoord] == '#':numNeighbors += 1 # 右上角的邻居是活的.if currentCells[leftCoord][y] == '#':numNeighbors += 1 # 左边的邻居还活着.if currentCells[rightCoord][y] == '#':numNeighbors += 1 # 右边的邻居还活着.if currentCells[leftCoord][belowCoord] == '#':numNeighbors += 1 # 左下角的邻居是活的.if currentCells[x][belowCoord] == '#':numNeighbors += 1 # 底层邻居还活着.if currentCells[rightCoord][belowCoord] == '#':numNeighbors += 1 # 右下角的邻居是活的.# 基于康威生命游戏规则的设定细胞:if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):# 有2或3个邻居的活细胞保持活力:nextCells[x][y] = '#'elif currentCells[x][y] == ' ' and numNeighbors == 3:# 有3个邻居的死细胞变成活的:nextCells[x][y] = '#'else:# 其他的东西都会死亡或保持死亡:nextCells[x][y] = ' 'time.sleep(1) # 增加1秒的停顿,以减少闪动.
4.11.1 逗号代码
def eggs(value):lists = ''for a in range(len(value) - 1):lists += str(value[a]) + ', 'lists += 'and ' + str(value[-1])return listsspam=['apple','bananas','tofu','cats']print (eggs(spam))
