How to convert a list to a list of tuples?

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

    Using slicing?

    L = [1, "term1", 2, "term2", 3, "term3"]
    L = zip(L[::2], L[1::2])
    
    print L
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-27 03:33

    List directly into a dictionary using zip to pair consecutive even and odd elements:

    m = [ 1, 2, 3, 4, 5, 6, 7, 8 ] 
    d = { x : y for x, y in zip(m[::2], m[1::2]) }
    

    or, since you are familiar with the tuple -> dict direction:

    d = dict(t for t in zip(m[::2], m[1::2]))
    

    even:

    d = dict(zip(m[::2], m[1::2]))
    
    0 讨论(0)
  • 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')]
    >>> 
    
    0 讨论(0)
  • 2020-11-27 03:38

    The below code will take care of both even and odd sized list :

    [set(L[i:i+2]) for i in range(0, len(L),2)]
    
    0 讨论(0)
  • 2020-11-27 03:44

    Try with the group clustering idiom:

    zip(*[iter(L)]*2)
    

    From https://docs.python.org/2/library/functions.html:

    The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

    0 讨论(0)
提交回复
热议问题