📜  在Python为矩阵添加自定义边框

📅  最后修改于: 2022-05-13 01:55:34.155000             🧑  作者: Mango

在Python为矩阵添加自定义边框

给定一个矩阵,任务是编写一个Python程序来打印具有自定义边框的每一行。

Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "|"
Output : | 4 5 6 |
         | 1 4 5 |
         | 6 9 1 |
         | 0 3 1 |
Explanation : Matrix is ended using | border as required.

Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "!"
Output : ! 4 5 6 !
         ! 1 4 5 !
         ! 6 9 1 !
         ! 0 3 1 !
Explanation : Matrix is ended using ! border as required.

方法#1:使用循环

在这里,我们使用内循环执行打印行元素的任务,由空格分隔。添加自定义边框的主要步骤是使用 +运算符连接起来的。

Python3
# Python3 code to demonstrate working of
# Custom Matrix Borders
# Using loop
  
# initializing list
test_list = [[4, 5, 6], [1, 4, 5], 
             [6, 9, 1], [0, 3, 1]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing border
bord = "|"
  
for sub in test_list:
    temp = bord + " "
  
    # inner row
    for ele in sub:
        temp = temp + str(ele) + " "
  
    # adding border
    temp = temp + bord
    print(temp)


Python3
# Python3 code to demonstrate working of
# Custom Matrix Borders
# Using * operator + loop
  
# initializing list
test_list = [[4, 5, 6], [1, 4, 5], 
             [6, 9, 1], [0, 3, 1]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing border
bord = "|"
  
for sub in test_list:
  
    # * operator performs task of joining
    print(bord, *sub, bord)


输出:

The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]
| 4 5 6 |
| 1 4 5 |
| 6 9 1 |
| 0 3 1 |

方法#2:使用*运算符+循环



在这种情况下,连接内部字符的任务是使用 *运算符执行的。

蟒蛇3

# Python3 code to demonstrate working of
# Custom Matrix Borders
# Using * operator + loop
  
# initializing list
test_list = [[4, 5, 6], [1, 4, 5], 
             [6, 9, 1], [0, 3, 1]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing border
bord = "|"
  
for sub in test_list:
  
    # * operator performs task of joining
    print(bord, *sub, bord)

输出:

The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]
| 4 5 6 |
| 1 4 5 |
| 6 9 1 |
| 0 3 1 |