我有一个列表,我想将此列表转换为地图
mylist = ["a",1,"b",2,"c",3]
mylist相当于
mylist = [Key,Value,Key,Value,Key,Value]
所以输入:
mylist = ["a",1,"b",2,"c",3]
输出:
mymap = {"a":1,"b":2,"c":3}
P.S:我已经编写了以下函数来完成相同的工作,但我想使用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
答案 0 :(得分:10)
使用iter
和dict-comprehension:
>>> mylist = ["a",1,"b",2,"c",3]
>>> it = iter(mylist)
>>> {k: next(it) for k in it}
{'a': 1, 'c': 3, 'b': 2}
使用zip
和iter
:
>>> dict(zip(*[iter(mylist)]*2)) #use `itertools.izip` if the list is huge.
{'a': 1, 'c': 3, 'b': 2}
答案 1 :(得分:4)
>>> mylist = ["a",1,"b",2,"c",3]
>>> zippedlist = zip(mylist [0::2],mylist [1::2]) #slicing magic
>>> zippedlist
[('a', 1), ('b', 2), ('c', 3)]
>>> dictedlist = dict(zippedlist)
>>> dictedlist
{'a': 1, 'c': 3, 'b': 2}
这是因为切片[start:stop:skip]
列表从0开始,跳过2
压缩
列表从1开始,跳过2
答案 2 :(得分:1)
要从列表中获取所有密钥,您可以执行以下操作:
keys = mylist[::2]
其中mylist [:: 2]通过迭代从索引0开始的mylist中的每个第二个元素来创建新列表。
要从列表中获取所有值,您可以执行以下操作:
vals = mylist[1::2]
其中mylist[1::2]
通过迭代从索引1开始的mylist中的每个第二个元素来创建新列表。
然后你可以使用dict和zip:
dict(zip(keys,vals)) # or all in one line
dict(zip(mylist[::2], mylist[1::2]))
zip会将["a","b","c"]
和[1,2,3]
两个列表和“拉链”放在一起,以提供类似
[("a",1), ("b", 2), ("c", 3)]
和dict
采用可迭代的对并将它们变成字典。
答案 3 :(得分:0)
使用压缩和循环: -
from itertools import compress
from itertools import cycle
def fun(mylist):
keys = compress(mylist,cycle([1,0]))
values = compress(mylist,cycle([0,1]))
mymap = dict(zip(keys,values))
return mymap
mylist = ["a",1,"b",2,"c",3]
fun(mylist)
{'a': 1, 'c': 3, 'b': 2}