在 Python 中將元組元素提升為另一個元組的冪
當需要將一個元組的元素提升為另一個元組的冪次時,可以使用“zip”方法和生成器表示式。
zip 方法獲取可迭代物件,將其聚合為一個元組,並將其作為結果返回。
生成器是一種建立迭代器的簡單方法。它自動實現一個具有“__iter__()”和“__next__()”方法的類,並跟蹤內部狀態以及在不存在可返回的值時引發“StopIteration”異常。
以下是同樣的演示:
示例
my_tuple_1 = ( 7, 8, 3, 4, 3, 2) my_tuple_2 = (9, 6, 8, 2, 1, 0) 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 tuple raised to power of another tuple is : ") print(my_result)
輸出
The first tuple is : (7, 8, 3, 4, 3, 2) The second tuple is : (9, 6, 8, 2, 1, 0) The tuple raised to power of another tuple is : (40353607, 262144, 6561, 16, 3, 1) > The first tuple is : (7, 8, 3, 4, 3, 2) The second tuple is : (9, 6, 8, 2, 1, 0) The tuple raised to power of another tuple is : (40353607, 262144, 6561, 16, 3, 1)
說明
- 定義了兩個元組,並顯示在控制檯上。
- 迭代這些列表,並使用“zip”方法將它們壓縮。
- 使用“**”運算子,從兩個元組中獲取第一個元素作為第二個元素的冪。
- 然後將其轉換為元組。
- 此操作被分配給一個變數。
- 此變數是要顯示在控制檯上的輸出。
廣告