要在python中映射的列表

Anu*_*rag 1 python dictionary list python-itertools

我有一个列表,我想将此列表转换为地图

mylist = ["a",1,"b",2,"c",3]
Run Code Online (Sandbox Code Playgroud)

mylist相当于

mylist = [Key,Value,Key,Value,Key,Value]
Run Code Online (Sandbox Code Playgroud)

所以输入:

mylist = ["a",1,"b",2,"c",3]
Run Code Online (Sandbox Code Playgroud)

输出:

mymap = {"a":1,"b":2,"c":3}
Run Code Online (Sandbox Code Playgroud)

PS:我已经编写了以下函数来完成同样的工作,但我想使用python的迭代器工具:

def fun():
    mylist = ["a",1,"b",2,"c",3]
    mymap={}
    count = 0
    for value in mylist:
        if not count%2:
            mymap[value] = mylist[count+1]
        count = count+1
    return mymap        
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 10

使用iter和字典理解:

>>> mylist = ["a",1,"b",2,"c",3]
>>> it = iter(mylist)
>>> {k: next(it) for k in it}
{'a': 1, 'c': 3, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

使用zipiter:

>>> dict(zip(*[iter(mylist)]*2)) #use `itertools.izip` if the list is huge.
{'a': 1, 'c': 3, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

相关:如何zip(*[iter(s)]*n)在Python 中工作