问题描述
我想在python中使用join函数(不是任何其他函数)将两个列表合并到嵌套列表中,假设列表的长度相等,例如:
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"]]
推荐答案
我认为您不理解str.join
的用途.
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.
下面是一个演示:
>>> strs = ['a', 'b', 'c']
>>> ''.join(strs)
'abc'
>>> '--'.join(strs)
'a--b--c'
>>>
这意味着您不会将str.join
用于尝试执行的操作.相反,您可以使用 zip
和列表理解:
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']]
>>>
但是请注意,如果您使用的是Python 2.x,则可能要使用 itertools.izip
而不是zip
:
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']]
>>>
就像Python 3.x zip
一样,itertools.izip
将返回迭代器(而不是像Python 2.x zip
这样的列表).这样可以提高效率,尤其是在处理较大的列表时.
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.
这篇关于在Python中将两个列表连接到元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!