现在的位置: 首页 > 综合 > 正文

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

2017年12月10日 ⁄ 综合 ⁄ 共 367字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

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

#方法一
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}

抱歉!评论已关闭.