# 蟒蛇 |將兩個列表連接成一個元組列表

| | | | | | |

`輸入： list1 = [1, 2, 3] list2 = [`a`,`b`, `c `] 輸出： [(1,`a`), (2,`b`), (3,`c`)] 輸入： list1 = [1, 2, 3, 4] list2 = [1, 4, 9] 輸出： [(1, 1), (2, 4), (3, 9), (4, ``)] `

` def ` ` 合併(list1, list2): `

` merge_list ` ` = ` ` [(list1 [i], list2 [i]) ` ` for ` ` i ` ` in ` ` range ` ` (` ` 0 ` `, ` ` len ` ` (list1))] `

` return ` ` merge_list `

` #驅動代碼`

` list1 ` ` = ` ` [` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `] `

` list2 ` ` = ` ` [` ` `a` ` `, ` ``b` ` `, ` ` `c` ` `] `

` print ` ` (merge (list1, list2 )) `

`[ (1, `a`), (2,`b`), (3, `c`)] `

` def ` ` 合併 (list1, list2): `

` merge_list ` ` = ` ` [] `

` for ` ` i ` ` in ` ` range ` ` (` ` max ` ` ((` ` len (list1), len (list2)))): `

`while 真: 嘗試 : `

` tup ` ` = ` ` (list1 [i], list2 [i]) `

` except ` ` IndexError: `

` if len (list1) > len (list2): `

` list2. append (``) `

` tup = (list1 [i], list2 [i]) `

` elif len （list1）< len (list2): `

` list1. append (``) `

` tup = (list1 [i], list2 [i]) `

` continue `

` merge_list.append (tup) break return merge_list # 驅動代碼 list1 = [ 1 , 2 , 3 代碼> ] `

` list2 = [ `a` ` `, ` `` b` ` ` , ` ` `c` ` `] `

` print ` ` (merge (list1, list2)) `

` [(1, `a`), (2,`b`), (3, `c`)] `

 ` def ` ` 合併 (list1, list2): `` ` ` merge_list ` ` = ` ` 元組 ` ` (` ` zip ` ` （列表1，李st2)) `` return ` ` merge_list ` ` # 驅動代碼 `` list1 ` ` = ` ` [` ` 1 ` `, ` ` 2 ` `, ` ` 3 ` `] `` list2 ` ` = ` ` [` ` `a` ` `, ` ``b` ` `, ` `` c` ` `] `` print ` ` (merge (list1, list2)) ` 退出：`((1, `a`), (2, `b`), (3,`c`)) ` 方法 #4： 使用 enumerate()，替代 zip()。 此方法使用兩個 for 循環遍歷列表並連接兩個列表。 ` def ` ` merge (list1 , list2): `` merge_list ` ` = ` ` [(p1, p2) ` ` for ` ` idx1, p1 ` ` in ` ` 枚舉 ` ` (list1) `` ` ` for ` ` idx2, p2 ` ` in ` ` enumer吃了` ` (list2) ` ` if ` ` idx1 ` ` = ` ` = ` ` idx2] `` return ` ` merge_list `` `` # 驅動代碼 `` list1 ` ` = ` ` [` ` 1 ` `, ` ` 2 ` ` , ` `3 ` `] `` list2 ` ` = ` ` [` ` `a` ` ` , ` ``b` ` `, ` ` `c` ` `] `` print ` ` (merge (list1, list2 )) `

`[ (1, `a`), (2,`b`) , (3, `c`)] `

` # 使用map()和lambda def listOfTuples (l1, l2): return list ( map ( lambda x, y: (x, y), l1, l2)) 驅動代碼 list1 = [ 1 , 2 , 3 ] `

` list2 = [ `a` , `b` ` `, ` `` c` ` ` ] `

` print ` ` (listOfTuples (list1, list2)) `

`[(1, `a`), (2,`b`), (3, `c`)] `