Python 中元組的加法


當需要相加元組時,可以使用“amp”和 lambda 函式。

map 函式將給定的函式/操作應用於可迭代物件(例如列表、元組)中的每一個物件。它返回一個列表作為結果。

匿名函式是未定義名稱的函式。

一般來說,Python 中的函式使用“def”關鍵字定義,但匿名函式使用“lambda”關鍵字定義。它採用一個表示式,但可以採用任意數量的引數。它使用該表示式並返回其結果。下面是它的演示:

示例

線上演示

my_tuple_1 = (11, 14, 54, 56, 87)
my_tuple_2 = (98, 0, 10, 13, 76)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

my_result = tuple(map(lambda i, j: i + j, my_tuple_1, my_tuple_2))

print("The tuple after addition is: ")
print(my_result)

輸出

The first tuple is :
(11, 14, 54, 56, 87)
The second tuple is :
(98, 0, 10, 13, 76)
The tuple after addition is:
(109, 14, 64, 69, 163)

說明

  • 定義了兩個元組,並在控制檯上顯示了它們。
  • 將 lambda 函式應用於這兩個元組的每個元素上,並使用“map”方法對映加法過程。
  • 然後將其轉換為元組。
  • 將其分配給一個值。
  • 在控制檯上顯示它。

更新時間:2021 年 3 月 12 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.