简体   繁体   English

列表到字典python中的第n个项目

[英]nth item in List to dictionary python

I am trying to create a dictionary from every nth element of a list with list's original index as key. 我正在尝试使用列表的原始索引作为键,从列表的每n个元素创建一个字典。 So for example: 因此,例如:

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

Now running 正在运行

dict(enumerate(l)).items() 

gives me: 给我:

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

which is what I want. 这就是我想要的。 However the problem begins when I want to now select every second value from l to do this, so I try 但是,当我现在想从l中选择第二个值来执行此操作时,问题就开始了,所以我尝试

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

which gives me 这给了我

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

but I do not want that, I want to preserve the original index when making a dictionary. 但是我不想要那样,我想在制作字典时保留原始索引。 What is the best way to do this? 做这个的最好方式是什么?

I want the following output 我想要以下输出

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

Use itertools.islice() on the enumerate() object: enumerate()对象上使用itertools.islice()

from itertools import islice

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

islice() gives you a slice on any iterator ; islice()为您提供了任何迭代器的切片; the above takes every second element: 以上是第二个要素:

>>> 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)])

(note that the output is as expected, but order is, as always, determined by the hash table ). (请注意,输出与预期的一样,但顺序通常由哈希表确定 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM