反转矩阵中每第 K 行的Python程序
给定一个矩阵,任务是编写Python程序来反转第 K 行。其中,K 是某个跨度值。
Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4
Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]
Explanation : Every 4th row is reversed.
Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 2
Output : [[5, 3, 2], [3, 6, 8], [3, 5, 2], [6, 3], [3, 7, 4], [9, 2]]
Explanation : Every 2nd row is reversed.
方法 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))
输出:
The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]
方法 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))
输出:
The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]