python的*号表达式
可变参数 —— *号实参,
同时遍历多个对象 —— zip
zip传入可变数量个实参
1、简单了解下*号传递实参
aL = ['aaa', 'bbb', 'ccc']
def f(a, b, c):
print(a, b, c)
f(1, 2, 3)
f(*['a', 'b', 'c'])
f(99, *[12, 21])
f(*aL)
输出为
2、 zip基础用法
L1 = ['aaa', 'bbb', 'ccc']
L2 = ['1', '2', '3']
for a , b in zip(L1, L2):
print(a+b)
输出为
3、zip结合*号实参,达到可变个实参效果
3.1
L1 = ['1', '2', '3', '4', '5', '6']
for a in zip(*([map(lambda x:x, L1)] * 2)):
print(a)
结果为
3.2
L1 = ['1', '2', '3', '4', '5', '6']
for a in zip(*([map(lambda x:x, L1)] * 3)): # 由于是迭代器,*3,代表被调用了3次next()
print(a)
结果为
4、zip同时遍历n个对象
思考一下,如下,如果不知道有确切的多少个列表,L1、L2.....Ln,那么此时就不能写在zip后面写明为zip(L1, L2, L3)了,这该如何处理呢?
假如LL=[L1, L2, L3 ..... Ln],该如何像后面的输出一样呢?
L1 = ['1', '2', '3', '4', '5', '6']
L2 = ['a', 'b', 'c', 'd', 'e', 'f']
L3 = ['A', 'B', 'C', 'D', 'E', 'F']
for a, b, c in zip(L1, L2, L3):
print(a+b+c)
输出为:
4.2
参考:
L1 = ['1', '2', '3', '4', '5', '6']
L2 = ['a', 'b', 'c', 'd', 'e', 'f']
L3 = ['A', 'B', 'C', 'D', 'E', 'F']
LL = [L1, L2, L3]
# L4 ... Ln
def sum(a):
n = a[0]
for x in a[1:]:
n = n+x
return n
for a in zip(*LL):
print(sum(a))
参考:
https://blog.csdn.net/weixin_41521681/article/details/103528136