004_012 Python 将列表中的元素交替的作为键和值来创建字典

来源:互联网 发布:网络电影众筹 编辑:程序博客网 时间:2024/06/05 16:30

代码如下:

#encoding=utf-8print '中国'#将列表中的元素交替的作为键和值来创建字典#方法一def dictfromlist(keysandvalues):    return dict(zip(keysandvalues[::2],keysandvalues[1::2]))lista =[1,2,3,4]print dictfromlist(lista)#方法二可迭代 速度更快def pairwise(iterable):    itnext = iter(iterable).next    while True:        yield itnext(),itnext()def dictfromiter(seq):    return dict(pairwise(seq))print dictfromiter(lista)

打印结果如下:

中国
{1: 2, 3: 4}
{1: 2, 3: 4}

0 0
原创粉丝点击