Python – K 元素反转切片
给定元素列表,执行 K 个元素的反向切片。
Input : test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18], K = 3 Output : [18, 16, 15] Explanation : 3 elements sliced from rear end. Input : test_list = [2, 4, 6, 8], K = 3 Output : [8, 6, 4] Explanation : 3 elements sliced from rear end, 8, 6 and 4.
方法#1:使用列表切片
这是可以执行此任务的方式之一。在此,我们使用列表切片的反转和负切片功能执行反向切片。
Python3
# Python3 code to demonstrate working of
# K elements Reversed Slice
# Using list slicing
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 6
# using double slice to solve problem.
# "-" sign for slicing from rear
res = test_list[-K:][::-1]
# printing result
print("The sliced list : " + str(res))
Python3
# Python3 code to demonstrate working of
# K elements Reversed Slice
# Using K elements Reversed Slice
from itertools import islice
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 6
# using reversed and islice to slice
# and then perform reverse
res = list(islice(reversed(test_list), K))
# printing result
print("The sliced list : " + str(res))
输出
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
The sliced list : [18, 16, 15, 12, 9, 3]
方法#2:使用 islice() + reversed()
这是解决此问题的功能方法。在此,我们使用 islice() 执行切片,然后使用 reversed() 反转列表。
Python3
# Python3 code to demonstrate working of
# K elements Reversed Slice
# Using K elements Reversed Slice
from itertools import islice
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 6
# using reversed and islice to slice
# and then perform reverse
res = list(islice(reversed(test_list), K))
# printing result
print("The sliced list : " + str(res))
输出
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
The sliced list : [18, 16, 15, 12, 9, 3]