How to convert a list to a list of tuples?

后端 未结 7 1774
陌清茗
陌清茗 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:32

    >>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
    # Create an iterator
    >>> it = iter(L)
    # zip the iterator with itself
    >>> zip(it, it)
    [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
    

    You want to group three items at a time?

    >>> zip(it, it, it)
    

    You want to group N items at a time?

    # Create N copies of the same iterator
    it = [iter(L)] * N
    # Unpack the copies of the iterator, and pass them as parameters to zip
    >>> zip(*it)
    

提交回复
热议问题