python列表解析-简洁高效的创表方式

python列表解析文档:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

列表解析:

  • 根据已有列表,简洁快速高效创建新列表。
  • 列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,在中括号[](列表符号) 中使用。

语法:
 样式:

  • [expression for i in iterable]
  • [expression for i in iterable if cond_expr]
  • [0 for i in range(10) ]  #10个值为0的表

 拆解:

  • expression 计算表达式,通过此得出每次遍历的值
  • for i in iterable 遍历表、数组
  • if cond_expr 判断表达式,用于条件判断(选填)
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']]

你可能感兴趣的:(python)