📜  Python - 用前缀交换 K 后缀

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

Python - 用前缀交换 K 后缀

给定一个列表,执行 K 前缀和后缀的交换。

例子:

方法#1:使用切片和范围交换

在这里,我们使用列表切片执行获取所需切片的任务,并执行范围交换以交换元素。这是解决此问题的就地方法。

Python3
# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using range swap + slice()
  
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# performing range swap
test_list[:K], test_list[len(
    test_list) - K:] = test_list[len(test_list) - K:], test_list[:K]
  
# printing result
print("After prefix suffix swap : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using slice notation
  
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# joining parts using slice
res = test_list[len(test_list) - K:] + \
    test_list[K: len(test_list) - K] + test_list[:K]
  
# printing result
print("After prefix suffix swap : " + str(res))


输出
The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]

方法#2:使用切片符号

在此,我们使用切片执行切片的每个列表来执行列表元素的重建。

蟒蛇3

# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using slice notation
  
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# joining parts using slice
res = test_list[len(test_list) - K:] + \
    test_list[K: len(test_list) - K] + test_list[:K]
  
# printing result
print("After prefix suffix swap : " + str(res))
输出
The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]