Joining two lists into tuples in python

前端 未结 3 746
旧时难觅i
旧时难觅i 2020-12-06 15:46

I want to use the join function in python (not any other function) to merge two lists into nested lists, assuming the lists are of equal length, for example:



        
相关标签:
3条回答
  • 2020-12-06 16:22

    I don't think you understand what str.join is for.

    str.join is a string method that takes an iterable (usually a list) of strings and returns a new string object that is a concatenation of those strings separated by the string that the method was invoked on.

    Below is a demonstration:

    >>> strs = ['a', 'b', 'c']
    >>> ''.join(strs)
    'abc'
    >>> '--'.join(strs)
    'a--b--c'
    >>>
    

    This means that you would not use str.join for what you are trying to do. Instead, you can use zip and a list comprehension:

    >>> list1 = [1, 2, 3]
    >>> list2 = ["a", "b", "c"]
    >>> [list(x) for x in zip(list1, list2)]
    [[1, 'a'], [2, 'b'], [3, 'c']]
    >>>
    

    Note however that, if you are on Python 2.x, you may want to use itertools.izip instead of zip:

    >>> from itertools import izip
    >>> list1 = [1, 2, 3]
    >>> list2 = ["a", "b", "c"]
    >>> [list(x) for x in izip(list1, list2)]
    [[1, 'a'], [2, 'b'], [3, 'c']]
    >>>
    

    Like the Python 3.x zip, itertools.izip will return an iterator (instead of a list like the Python 2.x zip). This makes it more efficient, especially when dealing with larger lists.

    0 讨论(0)
  • 2020-12-06 16:28
    list(map(list, zip(list1, list2)))
    
    0 讨论(0)
  • 2020-12-06 16:35

    Eureka! The join function you are looking for in this context, my friend, is the following:

    def join(l1, l2):
        return [list(x) for x in zip(l1, l2)]
    
    print join(list1, list2) 
    

    :-)

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