Python 中巢狀元組列的乘積


如果需要找到巢狀元組的累積列乘積,可以使用“zip”方法和一個巢狀生成器表示式。

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

zip 方法獲取可迭代物件,將它們聚合成一個元組,並將其作為結果返回。

以下是相同內容的演示——

示例

現場演示

tuple_1 = ((11, 23), (41, 25), (22, 19))
tuple_2 = ((60, 73), (31, 91), (14, 14))

print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)

my_result = tuple(tuple(a * b for a, b in zip(tup_1, tup_2))
   for tup_1, tup_2 in zip(tuple_1, tuple_2))

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

輸出

The first tuple is :
((11, 23), (41, 25), (22, 19))
The second tuple is :
((60, 73), (31, 91), (14, 14))
The tuple after product is :
((660, 1679), (1271, 2275), (308, 266))

說明

  • 定義了兩個元組的元組(或巢狀元組),並在控制檯上顯示了它們。
  • 對這兩個元組進行拉鍊和迭代,並對相應的值進行乘法運算。
  • 然後將其轉換為一個元組,並將其分配給一個變數。
  • 此變數作為控制檯上的輸出顯示。

更新日期:2021-03-11

191 人檢視

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.