List中的第n项到字典python

时间:2016-08-23 21:32:52

标签: python dictionary enumeration python-3.5

我正在尝试从列表的每个第n个元素创建一个字典,并将列表的原始索引作为键。例如:

l = [1,2,3,4,5,6,7,8,9]

正在运行

dict(enumerate(l)).items() 

给了我:

dict_items([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)])

这就是我想要的。但是,当我想从l中选择每一秒的值来执行此操作时问题就开始了,所以我尝试

dict(enumerate(l[::2])).items() 

给了我

dict_items([(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)])

但我不希望这样,我想在制作字典时保留原始索引。这样做的最佳方式是什么?

我想要以下输出

dict_items([(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)])

1 个答案:

答案 0 :(得分:4)

enumerate()对象上使用itertools.islice()

from itertools import islice

dict(islice(enumerate(l), None, None, 2)).items() 

islice()为您提供任何迭代器的切片;上面提到了每一个元素:

>>> from itertools import islice
>>> l = [1,2,3,4,5,6,7,8,9]
>>> dict(islice(enumerate(l), None, None, 2)).items()
dict_items([(0, 1), (8, 9), (2, 3), (4, 5), (6, 7)])

(请注意,输出符合预期,但顺序一如既往地为determined by the hash table)。