元组
- 元组数据类型几乎和列表数据类型一致,区别在于元组数据是不可变的,无法对元组中的变量元素进行修改、添加或删除。
- 元组在创建时使用()进行输入。
- 虽然不能改变元组元素,但能对存储元组的变量重新赋值
list()和tuple()函数
list()函数:返回传递值的列表形式
tuple()函数:返回传递值的元组形式
标识和id()函数
id()函数:返回变量的数字内存地址
传递引用
def adds(list_name):
list_name.append("Hello")
list1 = [1,2,3]
adds(list1)
print(list1)
输出结果:
[1, 2, 3, 'Hello']
>>>
adds函数在被调用时,并没有对list1进行重新赋值,但它直接修改了列表,这是因为虽然list1和list_name包含了不同的引用,但他们都指向相同的列表地址。
PS:append()、extend()、remove()、sort()、reverse()和其他列表方法都会就地修改列表
copy模块的copy()和deepcopy()函数
- copy()函数可以用来复制列表或者字典,而不只是复制引用
- 如果要复制的列表中包含了列表,可以使用deepcopy()函数()
import copy
list1 = [1,2,3,4]
print("list1的id地址>>" + str(id(list1)))
list2 = copy.copy(list1)
print("list2的id地址>>" + str(id(list2)))
list2[1] = 9
print(list2)
print(list1)
输出结果:
list1的id地址>>2101578121280
list2的id地址>>2101546495104
[1, 9, 3, 4][1, 2, 3, 4]
>>>
修改list2时就不会对list1进行修改,因为它们指向不同的id地址
Conway 生命游戏
细胞自动机:如果一个活的细胞与2个或3格活的细胞为邻,它下一步就还是活的,如果一个死的细胞恰好与3个活的细胞相邻,下一步也还是活的,其他情况下细胞都会死亡或保持死亡。
一组由规则控制的由离散细胞组成的行为,会创建一个能够自动变化的趣味动画
# Conway 生命游戏
import random, time, copy
WIDTH = 60
HEIGHT = 20 # 60 *20 的方格
# 创造一个存储细胞的列表
Cells = []
for x in range(WIDTH):
column = []
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append("#") #创建一个活的细胞 #表示
else:
column.append(" ") #创建一个死的细胞 空白表示
Cells.append(column)
while True: # 主程序
print("\n\n\n\n\n")
Cells_current = copy.deepcopy(Cells) #复制Cells
for y in range(HEIGHT): # 打印细胞状态
for x in range(WIDTH):
print(Cells_current[x][y], end="")
print()
for x in range(WIDTH):# 根据规则对细胞状态进行更新
for y in range(HEIGHT):
leftCod = (x - 1) % WIDTH
rightCod = (x + 1) % WIDTH
aboveCod = (y - 1) % HEIGHT
belowCod = (y + 1) % HEIGHT
numNeighbors = 0 # 计算细胞邻居中活细胞的个数
if Cells_current[leftCod][aboveCod] == "#":
numNeighbors += 1
if Cells_current[x][aboveCod] == "#":
numNeighbors += 1
if Cells_current[rightCod][aboveCod] == "#":
numNeighbors += 1
if Cells_current[leftCod][y] == "#":
numNeighbors += 1
if Cells_current[rightCod][y] == "#":
numNeighbors += 1
if Cells_current[leftCod][belowCod] == "#":
numNeighbors += 1
if Cells_current[x][belowCod] == "#":
numNeighbors += 1
if Cells_current[rightCod][belowCod] == "#":
numNeighbors += 1
# 更新细胞状态
if Cells_current[x][y] == "#" and (numNeighbors == 2 or numNeighbors == 3):
Cells[x][y] = "#"
elif Cells_current[x][y] == " " and numNeighbors == 3:
Cells[x][y] = "#"
else:
Cells[x][y] = " "
time.sleep(1) # 暂停1s