#l列表推导式 oho=[1,2,3] for i in range(len(oho)): oho[i]=oho[i]*2 print(oho)#[2, 4, 6] #推导式[变量 for 变量 in 循环次数] #最终导入的值是推导式中的第一个变量即i*2 oho=[i*2 for i in oho] print(oho)#[4, 8, 12] x=[i for i in range(5)] print(x)#[0, 1, 2, 3, 4] x=[i*2 for i in range(5)] print(x)#[0, 2, 4, 6, 8]最后的值在于i*2 #将值导入空列表 x=[] for i in range(5): x.append(i+1) print(x)#[1, 2, 3, 4, 5] #字符串 y=[i*2 for i in "你好"] print(y)#[‘你你‘, ‘好好‘] #将字符转换为对应的ascll码值(ord()) code=[ord(c) for c in "HOLLOa"] print(code)#[72, 79, 76, 76, 79, 97] #二维列表 mat=[ [1,2,3], [4,5,6], [7,8,9]] #获取二维列表的行 cod=[row[1] for row in mat] print(cod)#[2, 5, 8] #列表对角线上元素 dia=[mat[i][i] for i in range(len(mat))] print(dia)#[1, 5, 9] dia2=[mat[i][2-i] for i in range(len(mat))] print(dia2) print(len(mat))
# 列表7 # 推导式2 s = [[0] * 3] * 3 print(s) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] s[1][1] = 1 print(s) # [[0, 1, 0], [0, 1, 0], [0, 1, 0]] # 这个是引用列表,所以改变的是二维中的每一行[1]的值 # 创建二维列表 A = [0] * 3 for i in range(3): A[i] = [0] * 3 print(A) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] A[1][1] = 1 print(A) # [[0, 0, 0], [0, 1, 0], [0, 0, 0]] S = [[0] * 3 for i in range(3)] S[1][1] = 1 print(S) # [[0, 0, 0], [0, 1, 0], [0, 0, 0]] # 推导式2 even = [i for i in range(10) if i % 2 == 0] print(even) # [0, 2, 4, 6, 8] w = ["ze", "shan", "zhen"] W = [i for i in w if i[0] == "z"] print(W) # [‘ze‘, ‘zhen‘] # 嵌套列表推导式 mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] zk = [lie for row in mat for lie in row] print(zk) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # 套娃添加 mk = [] for row in mat: for lie in row: mk.append(lie) print(mk) # [1, 2, 3, 4, 5, 6, 7, 8, 9] d = [x + y for x in "fince" for y in "nihao"] print(d)#[‘fn‘, ‘fi‘, ‘fh‘, ‘fa‘, ‘fo‘, ‘in‘, ‘ii‘, ‘ih‘, ‘ia‘, ‘io‘, ‘nn‘, # ‘ni‘, ‘nh‘, ‘na‘, ‘no‘, ‘cn‘, ‘ci‘, ‘ch‘, ‘ca‘, ‘co‘, ‘en‘, ‘ei‘, ‘eh‘, ‘ea‘, ‘eo‘] #将0-10之间偶数与能被三整除的数组成列表 b=[[x,y] for x in range(10) if x%2==0 for y in range(10) if y%3==0] print(b) #[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], # [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]
原文:https://www.cnblogs.com/H-Yan/p/14125232.html