Python – 后第 K 个元素
给定一个列表,任务是从后端提取所有第 K 个元素。
Input : test_list = [3, 4, 5, 2, 1], K = 2
Output : [1, 5, 3]
Explanation : Every 2nd elements are extracted from rear starting from 1.
Input : test_list = [3, 4, 5], K = 1
Output : [5, 4, 3]
Explanation : Every elements are extracted from rear starting from 1.
方法#1:使用循环
解决这个问题的方法很粗暴。在此,我们反转然后执行迭代以获取每个 Kth 多个元素。
# Python3 code to demonstrate working of
# Rear Kth elements
# Using loop
# initializing list
test_list = [3, 5, 7, 9, 10, 2, 8, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Rear Kth elements
res = []
test_list.reverse()
for idx, ele in enumerate(test_list):
# Extracting elements divisible by K
if idx % K == 0:
res.append(ele)
# printing result
print("Rear Kth elements : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]
方法#2:使用列表切片
这是此问题的速记版本解决方案。我们使用 list slicing skip 的力量来跳过第 K 个元素,并将其反转。
# Python3 code to demonstrate working of
# Rear Kth elements
# Using list slicing
# initializing list
test_list = [3, 5, 7, 9, 10, 2, 8, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Rear Kth elements
# Starting slicing from Rear (-1) and extracting all Kth elements
res = test_list[-1::-K]
# printing result
print("Rear Kth elements : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]