4、列表
列表、元组
1)列表数据类型
列表是值的集合,类似于数组,但列表包含的值可以是任何类型的组合,而数组只能是一种类型。这是python与其它结构化语言不同的区别之一。
list = [‘xxx’,nnn,fff,True,None]
多重列表 list =[[0,2,3],[‘xxx’,’ppp’,’ccc’]]
取列表中单个值:list[nu]_下标
负数索引下标:从列表末尾往前的顺序。
切片和子列表:list[0:4],之间用冒号。
得到列表长度:len(list)
改变列表中的值:指定下标修改
列表连接和复制:+操作 *操作
删除列表值: del list[nu]
del 也可用来删除简单变量。
2)使用列表
用于存储相似重复的信息。
测试程序 test_401.py
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
'(Or enter nothing to stop):')
name = input()
if name == '':
break
catNames = catNames + [name] #list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
for i in range(len(catNames)):
print('Index ' + str(i) + ' cat is: ' + catNames[i])
列表用于循环取数
in 和 not in 操作符:
测试程序 test_402.py
myPets = ['Zophie','Pooka','Fat-Tail','Big-Yellow']
for index,item in enumerate(myPets):
print('Index ' + str(index) + ' in myPets is :' + item)
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + 'is my pet.')
多重赋值
enumerate()函数与列表
random.choice() 随机选择
random.shuffle()随机排序
3)增强的赋值操作
+= -= *= /= %=
数值类型均可用。
字符串和列表 可以用+=和*=
4)列表方法
方法和函数一样。类的附属处理称为方法。
index() :在列表中查找值的位置
append():在列表尾部添加值
insert():在列表任意位置添加值
remove():在列表中删除值,有重复值只删除第一个。与del对比。
sort() :对列表中值进行排序 数值排序和字典排序
reverse():对列表值进行反转
5)程序:神奇8球和列表
测试程序:test_403.py
import random
messages = ['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']
print(messages[random.randint(0,len(messages)-1)])
6)序列数据类型
序列数据类型包括列表、字符串、由range()返回的范围对象,以及元组
字符串可以视同为列表,简单操作均可用于字符串,但方法不能用于字符串
可变和不可变数据类型:即序列中的单元值是否可更改,列表是可变的,字符串是不可变的,不能更改。改变字符串相当于重构一个新字符串,使用切片和连接。
元组数据类型:元组是列表的不可变形式。
元组的不可变性,可以在系统级实现一些优化,其运行速度高于列表。
用list()和tuple()来实现列表和元组的类型转换。
7)引用
列表赋值是引用,字符串是值复制。
标识和id()函数:每一个变量都是引用,都指向值的标识,id()显示标识。
传递引用,
测试程序 test_404.py
def eggs(someParameter):
someParameter.append('Hello')
print('eggs para id:' + str(id(someParameter)))
spam = [1,2,3]
eggs(spam)
print(spam)
print('spam id:' + str(id(spam)))
Copy()和deepcopy()函数
8)小程序:Conway的生命游戏
测试程序 test_405.py
# Conway's Game of Life
import random, time, copy
WIDTH = 60
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):
if random.randint(0,1) == 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.
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 an WIDTH - 1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# Count number of living neighbors:
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(2) # Add a 1-second pause to reduce flickering.