Python基础之列表深浅复制和列表推导式
一、列表深浅复制:
浅拷贝内存图如下:
深拷贝内存图如下:
二、列表推导式:
实例:
""" 列表推导式 练习:exercise01 """ list01 = [3,5,6,7,9] # 需求:创建新列表,每个元素是list01中的元素的平方 list02 = [] for item in list01: list02.append(item ** 2) print(list02) # 语法:[对变量的操作 for 变量名 in 可迭代对象] list03 = [item ** 2 for item in list01] list01 = [3,5,6,7,9] # 需求:创建新列表,如果元素是偶数,则将每个元素的元素的平方存入新列表 list02 = [] for item in list01: if item % 2 == 0: list02.append(item ** 2) list03 = [item ** 2 for item in list01 if item % 2 == 0] print(list03)
实例二:
# 字母全匹配 list01 = ["a", "b", "c"] list02 = ["A", "B", "C"] # list03 = [] # for r in list01: # for c in list02: # list03.append(r+c) list03 = [r + c for r in list01 for c in list02] print(list03) # 练习:实现两个列表的全排列 #["香蕉","苹果","哈密瓜"] ["可乐","牛奶"] list03 = ["香蕉","苹果","哈密瓜"] list04 = ["可乐","牛奶"] list05 = [] for r in list03: for c in list04: list05.append(r+c) list06 = [r+c for r in list03 for c in list04] print(list06)