内容简介:zip即将多个可迭代对象组合为一个可迭代的对象,每次组合时都取出对应顺序的对象元素组合为元组,直到最少的对象中元素全部被组合,剩余的其他对象中未被组合的元素将被舍弃。示例结果:可以看到我们由
zip即将多个可迭代对象组合为一个可迭代的对象,每次组合时都取出对应顺序的对象元素组合为元组,直到最少的对象中元素全部被组合,剩余的其他对象中未被组合的元素将被舍弃。
keys = ['one', 'two', 'three'] values = [1, 2, 3] d = zip(keys, values) print(list(d)) 复制代码
示例结果:
[('one', 1), ('two', 2), ('three', 3)]
复制代码
可以看到我们由 zip
模拟了一个类似字典的一一对应的元组迭代对象,并将其转化为 list
类型查看,当然我们可以利用获取迭代对象生成真正的键值字典:
keys = ['one', 'two', 'three']
values = [1, 2, 3]
d = zip(keys, values)
D = {}
for key, value in d:
print(key, value)
D[key] = value
print(D)
复制代码
示例结果:
one 1
two 2
three 3
{'one': 1, 'two': 2, 'three': 3}
复制代码
我们可以利用for循环迭代赋值给字典完成对应的键值映射,在 Python 3中我们还可以用一句话就可以完成 D = dict(zip(keys,values))
.
*zip
当我们想回退为迭代器组合之前的状态时,我们可以利用 *
“解压”现在“压缩”过的新的迭代对象
keys = ['one', 'two', 'three', 'four'] values = [1, 2, 3] d = zip(keys, values) older = zip(*d) print(list(older)) 复制代码
“解压”结果:
[('one', 'two', 'three'), (1, 2, 3)]
复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Elements of Statistical Learning
Trevor Hastie、Robert Tibshirani、Jerome Friedman / Springer / 2009-10-1 / GBP 62.99
During the past decade there has been an explosion in computation and information technology. With it have come vast amounts of data in a variety of fields such as medicine, biology, finance, and mark......一起来看看 《The Elements of Statistical Learning》 这本书的介绍吧!