简体   繁体   中英

Joining two lists into tuples in python

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:

list1 = [1, 2, 3]

list2 = ["a", "b", "c"]

I want it to produce a new list like this:

[[1,"a"], [2,"b"], [3,"c"]]

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.

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) 

:-)

list(map(list, zip(list1, list2)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM