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.