📜  反转矩阵中每第 K 行的Python程序

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

反转矩阵中每第 K 行的Python程序

给定一个矩阵,任务是编写Python程序来反转第 K 行。其中,K 是某个跨度值。

方法 1:使用reversed()循环

在这里,我们对每一行进行迭代,如果找到第 K 行,则使用 reverse() 执行它的反转。



例子:

Python3
# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using reversed() + loop
  
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], 
             [3, 6], [3, 7, 4], [2, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
res = []
for idx, ele in enumerate(test_list):
  
    # checking for K multiple
    if (idx + 1) % K == 0:
  
        # reversing using reversed
        res.append(list(reversed(ele)))
    else:
        res.append(ele)
  
# printing result
print("After reversing every Kth row: " + str(res))


Python3
# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using Slicing + list comprehension
  
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], 
             [3, 6], [3, 7, 4], [2, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# using enumerate() to get index and elements.
# list comprehension to perform of iteration
res = [ele[::-1] if (idx + 1) % K == 0 else ele for idx,
       ele in enumerate(test_list)]
  
# printing result
print("After reversing every Kth row: " + str(res))


输出:

方法 2:使用切片列表理解

在此,使用字符串切片执行反转任务,并使用列表理解作为执行迭代任务的速记。

例子:

蟒蛇3

# Python3 code to demonstrate working of
# Reverse Kth rows in Matrix
# Using Slicing + list comprehension
  
# initializing list
test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], 
             [3, 6], [3, 7, 4], [2, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# using enumerate() to get index and elements.
# list comprehension to perform of iteration
res = [ele[::-1] if (idx + 1) % K == 0 else ele for idx,
       ele in enumerate(test_list)]
  
# printing result
print("After reversing every Kth row: " + str(res))

输出: