for i in range(0,4,2):
print(i)
print(i+1)
从0到4,选择循环间隔为2
结果:
a=[1,2,3,4,5]
b=[1,2,3,4,5,6]
result=[(a1,b1) for a1 in a for b1 in b]
print(result)
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6)]
举个简单的例子:
a,b=(1,2)
这就是元组拆包。
其它多种运用:
a,b,*rest=(1,2,3,4,4,5)
这种拆包方法是,将剩余的元素赋值给了rest,方法就是,*+rest
1
ct=[(1,2,(1,2)),(1,2,(1,4)),(1,2,(1,3)),(1,5,(1,2)),(1,3,(1,2))]
for one,two,(three,four) in ct:
print((one,two,(three,four)))
2
data=[(1,2,(1,2)),(1,4,(1,3)),(2,2,(1,5)),(7,2,(3,2)),(5,2,(4,2))]
fmt="{0}|{1}|{2}"
for one,two,(three,four) in data:
print(fmt.format(one,three,four))
3
data=[(1,2,(1,2)),(1,4,(1,3)),(2,2,(1,5)),(7,2,(3,2)),(5,2,(4,2))]
fmt="{:.3f}|{:.5f}|{:.3f}" # :.Xf 可以设置精度
for one,two,(three,four) in data:
print(fmt.format(one,three,four))
6,可变参数
这个很有用,在定义函数的时候,传入参数,1个或是2个还好,可是要传入一个列表的时候会很繁琐,上这时候可变参数就可以起作用。
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
这种每次使用的时候都要组装一个numbers(元组或是列表)
下面还有一种定义方式:
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
仅仅在前面加一个*号就可以实现calc(1,2,3,4)这种操作啦
如果输入是list或是元组,在前面加上*即可当做输入