zip用法
zip即将多个可迭代对象组合为一个可迭代的对象,每次组合时都取出对应顺序的对象元素组合为元组,直到最少的对象中元素全部被组合,剩余的其他对象中未被组合的元素将被舍弃。
keys = ['one', 'two', 'three', 'four']
values = [1, 2, 3]
d = zip(keys, values)
print(d)
#<zip object at 0x0000023A69F436C8>
for item in d:
print(item)
#('one', 1)
#('two', 2)
#('three', 3)
*zip用法
从已迭代的对象中还原至原来的对象,类似在压缩后“解压”。
# zip
keys = ['one', 'two', 'three', 'four']
values = [1, 2, 3]
d = zip(keys, values)
older = list(zip(*d))
print(older[1])
#(1, 2, 3)
print(older[0])
#('one', 'two', 'three')
*zip常见报错
以下代码会打印出item的值,同时报错:IndexError: list index out of range
keys = ['one', 'two', 'three', 'four']
values = [1, 2, 3]
d = zip(keys, values)
for item in d:
print(item)
older = list(zip(*d))
print(older[1])
print(older[0])
报错原因:
zip返回的值是一个迭代器指针,使用for循环后,将指针至于数据d的结尾,再转化为list时会out of range。
修改思路:
1. 重新zip一遍
keys = ['one', 'two', 'three', 'four']
values = [1, 2, 3]
d = zip(keys, values)
for item in d:
print(item)
d = zip(keys, values)
older = list(zip(*d))
print(older[1])
print(older[0])
#('one', 1)
#('two', 2)
#('three', 3)
#(1, 2, 3)
#('one', 'two', 'three')
2. 保存zip后数据d的地址,以便再次使用。
具体使用方法参考https://blog.csdn.net/Kelvin_Yan/article/details/86546784
ref:https://blog.csdn.net/Karven_/article/details/90216420
python2与python3差别https://blog.csdn.net/u012509485/article/details/78203784
Python zip()函数的一次踩坑记https://blog.csdn.net/benpaodelulu_guajian/article/details/81869462