python: combine 2 ordered lists into list of tuples

前端 未结 5 755
轮回少年
轮回少年 2021-01-17 05:04

I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the result[i] is (first[i], second[i]). Assume

相关标签:
5条回答
  • 2021-01-17 05:13

    Use zip:

    list(zip(first, second))
    Out[384]: [(1, 4), (2, 5), (3, 6)]
    
    0 讨论(0)
  • 2021-01-17 05:14

    You can use the built-in zip function:

    >>> first = [1,2,3]
    >>> second = [4,5,6]
    >>> list(zip(first, second))
    [(1,4), (2,5), (3,6)]
    
    0 讨论(0)
  • 2021-01-17 05:16
    >>> first = [1,2,3]
    >>> second = [4,5,6]
    >>> list =zip(first,second)
    >>> list
    [(1, 4), (2, 5), (3, 6)]
    

    or also for lists instead of tuple, using numpy

    >>> lista = [first,second]
    >>> import numpy as np
    >>> np.array(lista)
    array([[1, 2, 3],
           [4, 5, 6]])
    >>> np.array(lista)[:,0]
    array([1, 4])
    >>> np.array(lista)[:,1]
    array([2, 5])
    >>> np.array(lista)[:,2]
    array([3, 6])
    
    0 讨论(0)
  • 2021-01-17 05:21

    Use izip:

    >>> first = [1,2,3]
    >>> second = [4,5,6]
    
    >>> from itertools import izip
    >>> gen = izip(first, second)
    >>> [(i, j) for i, j in gen]
    [(1, 4), (2, 5), (3, 6)]
    
    0 讨论(0)
  • 2021-01-17 05:37

    Python has a function for that:

    >>> zip(first, second)
    [(1, 4), (2, 5), (3, 6)]
    

    zippedy-doo-dah

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