##列表推导式
列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为
生成新列表的元素,或者根据确定的判定条件创建子序列。
每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出
一个元组,就必须使用括号。
#在for循环中添加运算符来获得新列表,例一:
num = [2,4,8] i = [[i,i**2] for i in num] print(i) 打印结果>>>[[2, 4], [4, 16], [8, 64]]
#在for语句中对每个元素调用方法,例三:
love = [" qiao"," ling","yan "] i=[i.strip() for i in love] print(i) 打印结果>>>['qiao', 'ling', 'yan']
#for循环中制作过滤器,例四:
num = [3,5,8] i=[2*i for i in num if i < 6] print(i) 打印结果>>>[6,10]
#双重for循环,可写成了一行,例四:
num_1 = [3,5,8] num_2 = [-3,5,-8] i=[x*y for x in num_1 for y in num_2] print(i) 打印结果>>>[-9, 15, -24, -15, 25, -40, -24, 40, -64]
#一层for循环也可以起到列表相互运算的作用,例五:
num_1 = [3,5,8] num_2 = [-3,5,-8] num=[num_1[i] * num_2[i] for i in range(len(num_1))] print(num) 打印结果>>>[-9, 25, -64]
#列表推导式可以使用复杂表达式或嵌套函数
#>保留小数>3.14>保留3位小数到第5位小数,迭代3次,以字符串的形式输出
num=[str(round(355/113, i)) for i in range(2,6)] print(num) 打印结果>>>[3.14, 3.142, 3.1416, 3.14159]
#以下实例将3X4的矩阵列表转换为4X3列表,例一:
[[row[i] for row in matrix] for i in range(4)] 打印结果>>>[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
例二:
t = 123,"hi",333 print(t) u=t ,(222,0) print(u) 打印结果>>>(123, 'hi', 333) 打印结果>>>((123, 'hi', 333), (222, 0))
#同时遍历两个或更多的序列,可以使用 zip() 组合,例一:
s=["zhi","ling","1314"] z=["qiao","yan","520"] for x,y in zip(s,z): print("what is you name? ", x,y) what is you name? zhi qiao what is you name? ling yan what is you name? 1314 520
#同时遍历两个或更多的序列,可以使用 zip() 组合,例二:
s=["name","age","gender"] z=["lingyan","24","女"] for x,y in zip(s,z): print("what is you %s? "%x,y) what is you name? lingyan what is you age? 24 what is you gender? 女
#要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值: num = [5, 1, 4, 3, 2, 6] st = ["b","a","c","d","f"] for i in zip(sorted(set(num)),sorted(set(st))): print(i)
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'f')
错误提示:an't multiply sequence by non-int of type
'list' (非整数类型列表的非整数序列)