How to convert a list to a list of tuples?

后端 未结 7 1720
陌清茗
陌清茗 2020-11-27 02:52

I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.

This is the input list:



        
7条回答
  •  攒了一身酷
    2020-11-27 03:34

    Try this ,

    >>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
    >>> it = iter(L)
    >>> [(x, next(it)) for x in it ]
    [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
    >>> 
    

    OR

    >>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
    >>> [i for i in zip(*[iter(L)]*2)]
    [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
    

    OR

    >>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
    >>> map(None,*[iter(L)]*2)
    [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
    >>> 
    

提交回复
热议问题