用 Python 列表修改元組內容
如果需要修改元組列表,可以使用“zip”方法和列表推導。
zip 方法採用可迭代物件,將它們聚合到元組中,並將其作為結果返回。
列表推導是迭代遍歷列表並對列表執行操作的一種簡寫。
列表可以用來儲存異構值(即,任何資料型別的資料,如整數、浮點數、字串等)。元組列表基本上包含封閉在列表中的元組。
下面是對其演示 −
示例
my_list_1 = [('Hi', 1), ('there', 2), ('Jane', 3)] my_list_2 = [45, 67, 21] print("The first list is : ") print(my_list_1) print("The second list is : " ) print(my_list_2) my_result = [(i[0], j) for i, j in zip(my_list_1, my_list_2)] print("The modified list of tuple is : ") print(my_result)
輸出
The first list is : [('Hi', 1), ('there', 2), ('Jane', 3)] The second list is : [45, 67, 21] The modified list of tuple is : [('Hi', 45), ('there', 67), ('Jane', 21)]
說明
- 定義一個元組列表,並將其顯示在控制檯上。
- 定義另一個列表,並將其顯示在控制檯上。
- 這兩個列表被壓縮並被迭代。
- 然後將它轉換為一個列表。
- 此操作的資料儲存在變數中。
- 此變數是顯示在控制檯上的輸出。
廣告