简体   繁体   English

在Python中将两个列表连接到元组

[英]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: 我想在python中使用join函数(不是任何其他函数)将两个列表合并为嵌套列表,假设列表的长度相等,例如:

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的用途。

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. str.join是一个字符串方法,它接收一个可迭代的字符串(通常是一个列表),并返回一个新的字符串对象,该对象是由被调用该方法的字符串分隔的那些字符串的串联。

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. 这意味着您将不会使用str.join进行操作。 Instead, you can use zip and a list comprehension : 相反,您可以使用zip列表理解

>>> 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 : 但是请注意,如果您使用的是Python 2.x,则可能要使用itertools.izip而不是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 ). 像Python 3.x zipitertools.izip将返回一个迭代器(而不是像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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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