目标:打印两个列表的值python
使用while True:web
i=['d','e','f','g']
t=['a','b','c']
n=0
while n < max(len(i),len(t)):
try:
print(i[n])
print(t[n])
except IndexError:
break
n+=1ide
使用for循环结合zip函数:函数
for k,v in zip(i,t):
print(k)
print(v)spa
打印结果:.net
d
a
e
b
f
corm
使用help(zip)查看函数模块使用方法对象
zip:blog
定义:zip([seql, ...])接受一系列可迭代对象做为参数,将对象中对应的元素打包成一个个tuple(元组),而后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同ip
通俗点就是把几个列表(0或者1或者多个)的对应位置的元素组成新的tuple, 这些新的tuple 构成一个list
有参数的形式:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
输出:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)] 从这个结果能够看出zip函数的基本运做方式。
#无参数时,x = zip() print x#结果是:[]
x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy
输出:
[(1, 4), (2, 5), (3, 6)]从这个结果能够看出zip函数的长度处理方式。
#zip压缩解压缩的用法:
Python2的写法:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
u = zip(*xyz)
print u
# 输出:
# [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
python3的写法:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz=zip(x,y,z)
u = zip(*xyz)
print(u)
<zip object at 0x0000000002412F48>
因此在python3中须要转成列表list(zip(x,y,z)),正确的结果以下
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
# xyz = zip(x, y, z)
xyz=list(zip(x,y,z))
u = list(zip(*xyz))
print(u)
# # 输出:
# # [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
list(zip(*list(zip(x,y,z))))
a=list(zip([1,2,3],[4,5,6],[7,8,9]))
print(list(zip(*a)))
打印结果:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
通常认为这是一个unzip的过程,它的运行机制是这样的:
在运行zip(*xyz)以前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
那么,zip(*xyz) 等价于 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))
因此,运行结果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
注:在函数调用中使用*list/tuple的方式表示将list/tuple分开,做为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数)
x = [1, 2, 3]
r = zip(* [x] * 3)print r
输出:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
它的运行机制是这样的:
[x]生成一个列表的列表,它只有一个元素x
[x] * 3生成一个列表的列表,它有3个元素,[x, x, x]
zip(* [x] * 3)的意思就明确了,zip(x, x, x)
补充:zip的压缩与解压缩
# 解压
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
a=list(zip([1,2,3],[4,5,6],[7,8,9])) #list(zip(x,y,z))
b=zip(*a)
for i in b:
print(i)
#打印结果
# (1, 2, 3)
# (4, 5, 6)
# (7, 8, 9)
# # 压缩
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
a=list(zip([1,2,3],[4,5,6],[7,8,9])) #list(zip(x,y,z))
print(list(zip(*a)))
#打印结果
#[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
参考地址: https://blog.csdn.net/heifan2014/article/details/78894729
https://blog.csdn.net/qq_37383691/article/details/75271172 -->经典
https://blog.csdn.net/shomy_liu/article/details/46968651
https://blog.csdn.net/heifan2014/article/details/78894729
http://www.pythonclub.org/python-files/zip ---zipfile模块