#列表可以包含列表值 spam=[['cat','bat'],['dog','pig']] print(spam[0][1]) #bat spam=['cat','bat','dog','pig'] print(spam[0:-1]) #['cat', 'bat', 'dog'] #删除列表中的某个值 spam=['cat','bat','dog','pig'] print(spam) #['cat','bat','dog','pig'] del spam #已经删除整个列表 # print(spam) # NameError: name 'spam' is not defined spam=['cat','bat','dog','pig'] del spam[3] print(spam) #['cat', 'bat', 'dog'] # 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: print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter "q" to stop.):') name = input() if name == '': break catNames = catNames + [name] # list concatenation print('The cat names are:') for name in catNames: print(' ' + name) # 4.2.3 多重赋值技巧 cat=['fat','black','loud'] size=cat[0] color=cat[1] disposition=cat[2] # n. 性情,性格;倾向,癖性 #多重赋值方法:变量数目与列表长度必须严格相等 size,color,disposition = cat print(size) print(color) print(disposition) # 4.2.4 enumerate()函数:返回2个值,列表中表项的索引+列表中的表项自身 cat=['fat','black','loud'] for index,item in enumerate(cat): print(index) print(item) # 4.2.5 random.choice():从列表中返回一个随机的表项 import random pets=['cat','dog','pig'] random.choice(pets) print( random.choice(pets) ) print( random.choice(pets) ) print( random.choice(pets) ) # random.shuffle():对列表中的表项重新/随机排序 import random pets=['cat','dog','pig'] random.shuffle(pets) print(pets) #某次结果:['pig', 'dog', 'cat'] random.shuffle(pets) print(pets) #某次结果:['cat', 'pig', 'dog'] # 4.4 方法 ## 4.4.1 index()方法:在列表中查找值 spam=['hello','hi','howdy','heyas'] print(spam.index('hi')) ##如果有重复的表项,返回它出现的第一个索引 spam=['hello','hi','hello','howdy','heyas'] print(spam.index('hello')) ## 4.6 序列类型 ##适用于列表的也适用于字符串 name='Zophie' print(name[0]) print(name[-2]) print(name[0:4]) if 'Zop' in name: print('True') for i in name: print(i) ## 4.6.1 可变和不可变的类型 name='Zophie a cat' newName=name[0:7]+'the'+name[8:] print(name) print(newName) ## 4.6.2 元组内只有一个值的情况下,在括号内加上 print(type(('apple',))) #<class 'tuple'> print(type(('apple'))) #<class 'str'> # 4.6.3 用list()和tuple()函数来转换类型 print ( tuple(['cat','dog','pig']) ) #('cat', 'dog', 'pig') print ( list(('cat','dog','pig')) ) #['cat', 'dog', 'pig'] print ( list('hello') ) #['h', 'e', 'l', 'l', 'o'] # 4.7 引用 ##整数是不可变的 spam=43 chess=spam print(id(chess)) #2624911246896 print(id(spam)) #2624911246896 spam=100 print(chess) print(spam) print(id(chess)) #2624911246896 print(id(spam)) #1728411143504 ##列表是可变的 spam=[0,1,2,3,4,5] chess=spam chess[1]='hello' print(chess) #[0, 'hello', 2, 3, 4, 5] print(spam) #[0, 'hello', 2, 3, 4, 5] print(id(chess)) #2007464569600 print(id(spam)) #2007464569600 ## 4.7.1 id()函数 print(id('hello')) #2258180235248 bacon='holiday' #2258180237552 print(id(bacon)) pets=['cat','dog'] print(id(pets)) #2258180314944 pets.append('pig') print(id(pets)) #2258180314944 pets=['cat','dog','pig'] print(id(pets)) #2915067828224 #4.7.3 copy模块的copy() import copy spam=['A','B','C','D'] print(id(spam)) #2606676384512 chess=copy.copy(spam) #2663137942016 print(id(chess)) chess[1]=42 print(chess) #['A', 42, 'C', 'D'] print(spam) #['A', 'B', 'C', 'D'] ##deepcopy():要复制的列表里边的列表,嵌套列表 import copy spam=[[1,2],[3,4],'C','D'] a=copy.copy(spam) b=copy.deepcopy(spam) print(id(spam[0])) #2068719364864 print(id(a[0])) #2068719364864 print(id(b[0])) #2068719411136 # 4.8 Conway的生命游戏 # Conway's Game of Life import random, time, copy WIDTH = 60 #格子60宽,20高 HEIGHT = 20 # Create a list of list for the cells: nextCells = [] for x in range(WIDTH): column = [] # Create a new column. 一列列的成为一整个格子 for y in range(HEIGHT): #HEIGHT为循环长度 if random.randint(0, 1) == 0: #如果随机值为0,添加“#”,代表细胞活着 column.append('#') # Add a living cell. else: column.append(' ') # Add a dead cell. nextCells.append(column) # nextCells is a list of column lists. while True: # Main program loop. print('\n\n\n\n\n') # Separate each step with newlines.5行空格 currentCells = copy.deepcopy(nextCells) # Print currentCells on the screen: for y in range(HEIGHT): #一行一行的打印出来 for x in range(WIDTH): print(currentCells[x][y], end='') # Print the # or space. print() # Print a newline at the end of the row. # Calculate the next step's cells based on current step's cells: for x in range(WIDTH): for y in range(HEIGHT): # Get neighboring coordinates: 上下细胞索引:利用取模运算实现环绕 # `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1 leftCoord = (x - 1) % WIDTH rightCoord = (x + 1) % WIDTH aboveCoord = (y - 1) % HEIGHT belowCoord = (y + 1) % HEIGHT # Count number of living neighbors:每个细胞有8个邻居 numNeighbors = 0 #邻居数量 if currentCells[leftCoord][aboveCoord] == '#': numNeighbors += 1 # Top-left neighbor is alive. if currentCells[x][aboveCoord] == '#': numNeighbors += 1 # Top neighbor is alive. if currentCells[rightCoord][aboveCoord] == '#': numNeighbors += 1 # Top-right neighbor is alive. if currentCells[leftCoord][y] == '#': numNeighbors += 1 # Left neighbor is alive. if currentCells[rightCoord][y] == '#': numNeighbors += 1 # Right neighbor is alive. if currentCells[leftCoord][belowCoord] == '#': numNeighbors += 1 # Bottom-left neighbor is alive. if currentCells[x][belowCoord] == '#': numNeighbors += 1 # Bottom neighbor is alive. if currentCells[rightCoord][belowCoord] == '#': numNeighbors += 1 #Bottom-right neighbor is alive. # Set cell based on Conway's Game of Life rules: if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3): # Living cells with 2 or 3 neighbors stay alive: nextCells[x][y] = '#' elif currentCells[x][y] == ' ' and numNeighbors == 3: # Dead cells with 3 neighbors become alive: nextCells[x][y] = '#' else: # Everything else dies or stays dead: nextCells[x][y] = ' ' time.sleep(1) # Add a 1 second pause to reduce flickering.时间暂停1秒
第四章 列表【Python编程快速上手】
最新推荐文章于 2024-06-14 23:48:57 发布