python列表解析文档:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
列表解析:
语法:
样式:
拆解:
squ = []
for i in iterable:
if cond_expr:
squ.append(expression)
1.创建拥有5个值的一维表
def nrmlCreate():
# 普通方法
rsltList = []
vl = 0
for x in range(5):
rsltList.append(vl)
print("nrmlCreate>>>", rsltList)
def listComprehend():
# 列表解析
vl = 0
rsltList = [vl for i in range(5)]
print("listComprehend>>>", rsltList)
# 结果:
# nrmlCreate>>> [0, 0, 0, 0, 0]
# listComprehend>>> [0, 0, 0, 0, 0]
2.创建1~5所有整数+1的表
def nrmlCreate():
# 普通方法
rsltList = []
for x in range(1, 6):
rsltList.append(x + 1)
print("nrmlCreate>>>", rsltList)
def listComprehend():
# 列表解析
rsltList = [i + 1 for i in range(1, 6)]
print("listComprehend>>>", rsltList)
# 结果:
# nrmlCreate>>> [2, 3, 4, 5, 6]
# listComprehend>>> [2, 3, 4, 5, 6]
3.创建1~5整数中可以整除2的数的表
def nrmlCreate():
# 普通方法
rsltList = []
for x in range(1, 6):
if x % 2 == 0:
rsltList.append(x)
print("nrmlCreate>>>", rsltList)
def listComprehend():
# 列表解析
vl = 0
rsltList = [i for i in range(1, 6) if i % 2 == 0]
print("listComprehend>>>", rsltList)
# 结果:
# nrmlCreate>>> [2, 4]
# listComprehend>>> [2, 4]
4.创建一个二维数组表(嵌套列表解析)
def nrmlCreate():
# 普通方法
rsltList = []
rowNum = 2
columnNum = 3
vl = 0
for x in range(rowNum):
tempList = []
for y in range(columnNum):
tempList.append(vl)
rsltList.append(tempList)
print("nrmlCreate>>>", rsltList)
def listComprehend():
# 列表解析
rowNum = 2
columnNum = 3
vl = 0
rsltList = [[vl for y in range(columnNum)] for x in range(rowNum)]
print("listComprehend>>>", rsltList)
# 结果:
# nrmlCreate>>> [[0, 0, 0], [0, 0, 0]]
# listComprehend>>> [[0, 0, 0], [0, 0, 0]]
5.将两个一维表排列组合成一个二维表
listA = [1, 2]
listB = ["a", "b", "c"]
def nrmlCreate():
# 普通方法
rsltList = []
for x in listA:
for y in listB:
rsltList.append([x, y])
print("nrmlCreate>>>", rsltList)
def listComprehend():
# 列表解析
rsltList = [[x, y] for x in listA for y in listB]
print("listComprehend>>>", rsltList)
# 结果:
# nrmlCreate>>> [[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c']]
# listComprehend>>> [[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c']]