是否有将两个列表中的匹配索引对连接到 2D 列表的功能?



我正在努力定义我在文本中的意思,例如:

>>> list_1 = ["text text text", "text more text", "also text", "so much text"]
>>> list_2 = [0, 1, 0, 1]
>>> list_combine = some_function(list_1, list_2)
>>> print(list_combine)
[["text text text", 0],
["text more text", 1],
["also text", 0],
["so much text", 1]]

显然,人们可以简单地在范围(len(列表之一((上执行循环,但是我正在包含数千个项目的列表上执行此操作,并想知道是否有预先存在的函数可以更快地执行此操作?我假设 Numpy 可能拥有答案,但我不确定搜索词是否确实存在。

内置函数zip()执行您想要的操作。它生成元组而不是列表,您必须实际将生成的对象强制转换为list才能获得所需的输出,但是:

>>> list_1 = ["text text text", "text more text", "also text", "so much text"]
>>> list_2 = [0, 1, 0, 1]
>>> combined = list(zip(list_1, list_2))
>>> print(combined)
[('text text text', 0), 
('text more text', 1), 
('also text', 0), 
('so much text', 1)]

如果您真的需要列表而不是元组,您还可以使用列表推导通过强制元组来获取子列表,但这最终会

总体上慢一些:
combined = [list(tup) for tup in zip(list1, list2)]

请注意,zip()将在您为其馈送的最小迭代对象处截断。如果要压缩更大的可迭代对象,可以使用itertools.zip_longest()

最好将列表.zip()在一起,for遍历它们,并在每次迭代时追加。

list_1 = ["text text text", "text more text", "also text", "so much text"]
list_2 = [0, 1, 0, 1]
list_combine = []
for f, b in zip(list_1, list_2):
list_combine.append((f, b))
print(list_combine)

在此处查看代码片段

最新更新