Python 中的元組乘法


如果需要執行元組乘法,可以使用“zip”方法和生成器表示式。

zip 方法採用可迭代物件,將它們聚合到元組中,並將其作為結果返回。

生成器是建立迭代器的一種簡單方法。它自動透過“__iter__()”和“__next__()”方法實現一個類,並對內部狀態進行跟蹤,並在沒有可以返回的值時引發“StopIteration”異常。

以下是相同操作的演示:

示例

線上演示

my_tuple_1 = (23, 45, 12, 56, 78)
my_tuple_2 = (89, 41, 76, 0, 11)

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

my_result = tuple(elem_1 * elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The multiplied tuple is : ")
print(my_result)

輸出

The first tuple is :
(23, 45, 12, 56, 78)
The second tuple is :
(89, 41, 76, 0, 11)
The multiplied tuple is :
(2047, 1845, 912, 0, 858)

說明

  • 定義了兩個元組,並且在控制檯上顯示它們。
  • 對它們進行壓縮,然後對其進行迭代。
  • 第一個元組中的每個元素與第二個元組中的相應元素相乘。
  • 它被轉換為元組。
  • 將該操作分配給一個值。
  • 它在控制檯上作為輸出顯示。

更新於: 11-3-2021

1 千+ 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告