Python 中轉換到 N*N 元組矩陣


當需要將 N*N 元組轉換成矩陣時,可以使用簡單迴圈和 * 運算子。

可以使用 * 運算子獲取兩個值的乘積。還可以使用它來多次使用單個值並將其顯示在控制檯上。

以下是相同的演示 -

示例

線上演示

my_tuple_1 = ((11, 14), (0, 78), (33, 11), (10, 78))

print("The tuple of tuple is : ")
print(my_tuple_1)
N = 4
print("The value of N has been initialized to "+ str(N))

my_result = []
for tup in my_tuple_1 :
   my_result.append( tup +(0, ) * (N - len(tup)))
print("The tuple after filling in the values is: ")
print(my_result)

輸出

The tuple of tuple is :
((11, 14), (0, 78), (33, 11), (10, 78))
The value of N has been initialized to 4
The tuple after filling in the values is:
[(11, 14, 0, 0), (0, 78, 0, 0), (33, 11, 0, 0), (10, 78, 0, 0)]

說明

  • 定義一個巢狀元組並顯示在控制檯上。
  • 定義 'N' 的值並顯示。
  • 建立一個另一個空列表。
  • 遍歷巢狀元組,並在每個值後面新增 0,並重復 'N - len(tuple)' 次。
  • 將其分配給一個值。
  • 顯示在控制檯上。

更新於: 12-Mar-2021

363 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.