代码如下:
#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}