在 Python 中逐元素连接两个列表
pythonserver side programmingprogramming更新于 2026/1/13 5:00:17
Pyhton 具有出色的数据处理功能。在本文中,我们将了解如何按照列表中出现的顺序组合两个列表中的元素。
使用 zip
zip 函数可以将两个列表作为参数并将它们连接起来。我们设计了一个 for 循环来捕获这些组合并将它们放入一个新列表中。
示例
listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# 给定列表 A:", listA)
print("给定列表 B:",listB)
# 使用 zip
res = [i + j for i, j in zip(listA, listB)]
# 结果
print("The concatenated lists: ",res)
输出
运行上述代码得到以下结果 −
给定列表 A:['Outer-', 'Frost-', 'Sun-'] 给定列表 B:['Space', 'bite', 'rise'] 连接列表:['Outer-Space', 'Frost-bite', 'Sun-rise']
使用 lambda 和 map
map 函数将对传递给它的参数反复应用相同的函数。我们还将使用 lambda 函数通过 zip 将两个列表中的各个元素逐一组合起来。
示例
listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# 给定列表
print("给定列表 A: ",listA)
print("给定列表 B: ",listB)
# 使用 map
res = list(map(lambda(i, j): i + j, zip(listA, listB)))
# 结果
print("连接列表: ",res)
输出
运行上述代码得到以下结果−
给定列表 A:['Outer-', 'Frost-', 'Sun-'] 给定列表 B:['Space', 'bite', 'rise'] 连接列表:['Outer-Space', 'Frost-bite', 'Sun-rise']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

