【问题标题】:nth item in List to dictionary python列表中的第n项到字典python
【发布时间】:2016-12-30 20:43:09
【问题描述】:

我正在尝试从列表的每个第 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)])

【问题讨论】:

    标签: python dictionary enumeration python-3.5


    【解决方案1】:

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

    【讨论】:

    • 这样就可以了。谢谢。现在我将开始阅读此功能。
    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2014-12-12
    相关资源
    最近更新 更多