如何在 Python 中按元素逐個連線兩個列表


Python 有著出色的資料處理功能。在本文中,我們將會了解如何按照列表中存在的順序合併兩個列表中的元素。

使用 zip

zip 函式可以將兩個列表作為引數接收並將其連線起來。我們設計了一個 for 迴圈來捕獲這些組合並將它們放入一個新列表中。

示例

 即時演示

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use zip
res = [i + j for i, j in zip(listA, listB)]
# Result
print("The concatenated lists: ",res)

輸出

執行上面的程式碼,我們可以得到以下結果 −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']

使用 lambda 和 map

map 函式會反覆對傳遞給它的引數應用同一個函式。我們還將使用一個 lambda 函式,透過 zip 逐個合併兩個列表中的各個元素。

示例

 即時演示

listA = ["Outer-", "Frost-", "Sun-"]
listB = ['Space', 'bite', 'rise']
# Given lists
print("Given list A: ", listA)
print("Given list B: ",listB)
# Use map
res = list(map(lambda(i, j): i + j, zip(listA, listB)))
# Result
print("The concatenated lists: ",res)

輸出

執行上面的程式碼,我們可以得到以下結果 −

Given list A: ['Outer-', 'Frost-', 'Sun-']
Given list B: ['Space', 'bite', 'rise']
The concatenated lists: ['Outer-Space', 'Frost-bite', 'Sun-rise']

更新時間: 2020 年 5 月 20 日

1K+ 瀏覽

職業生涯開啟您的

完成課程即可獲得認證

開始
廣告