本文介绍了将列表转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
l = ["a", "b", "c", "d", "e"]
我想将此列表转换为字典,例如:
I want to convert this list to a dictionary like:
d = {"a": "b", "c": "d", "e": ""}因此,基本上,偶数将是关键,而几率将是值.我知道我可以通过非Python"方式(例如使用if语句的for循环)来完成此操作,但我相信应该有一种更"pythonic"的方式来完成此操作.因此,感谢您的帮助:)
So basically, the evens will be keys whereas the odds will be values. I know that I can do it in a "non-pythonic" way such as a for loop with if statements but I believe that there should be a more "pythonic" way to accomplish this. So, I appreciate any help :)
推荐答案使用常规的石斑鱼食谱,您可以这样做:
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))更多推荐
将列表转换成字典
发布评论