Converting a single ordered list in python to a dictionary, pythonically

前端 未结 6 740
悲&欢浪女
悲&欢浪女 2021-01-07 14:00

I can\'t seem to find an elegant way to start from t and result in s.

>>>t = [\'a\',2,\'b\',3,\'c\',4]
#magic
>>>print s
         


        
6条回答
  •  隐瞒了意图╮
    2021-01-07 14:44

    Guys, guys, use itertools. Your low-RAM users will thank you when the lists get large.

    >>> from itertools import izip, islice
    >>> t = ['a',2,'b',3,'c',4]
    >>> s = dict(izip(islice(t, 0, None, 2), islice(t, 1, None, 2)))
    >>> s
    {'a': 2, 'c': 4, 'b': 3}
    

    It might not look pretty, but it won't make unnecessary in-memory copies.

提交回复
热议问题