Python程序反转列表中的范围
给定一个列表,我们的任务是编写一个Python程序来反转列表中的一个范围。
例子:
Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 3, 9
Output : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]
Explanation : 8, 9, 2, 10, 12, 7 are reversed in list to 7, 12, 10, 2, 9, 8.
Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 8, 9
Output : [6, 3, 1, 8, 9, 2, 10, 7, 12, 4, 11]
Explanation : 12, 7 are reversed in list to 7, 12.
方法 #1:使用reverse() +循环
在此示例中,使用 reverse() 提取和反转子列表。接下来使用循环将范围元素替换为反向元素。
Python3
# Python3 code to demonstrate working of
# Reversing a range
# Using reverse() + loop
# initializing list
test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 3, 9
# reversing list and assigning the range
temp = test_list[strt:end]
temp.reverse()
for idx in range(strt, end):
test_list[idx] = temp[idx - strt]
# printing result
print("Range reversed range list : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Reversing a range
# Using list split + slicing
# initializing list
test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 3, 9
# Third arg. of split with -1 performs reverse
test_list[strt:end] = test_list[strt:end][::-1]
# printing result
print("Range reversed range list : " + str(test_list))
输出:
The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]
方法 #2:使用列表split() +切片
解决此问题的紧凑方法是使用列表拆分方式执行范围列表的反转,该方式仅反转切片所需的范围。
蟒蛇3
# Python3 code to demonstrate working of
# Reversing a range
# Using list split + slicing
# initializing list
test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 3, 9
# Third arg. of split with -1 performs reverse
test_list[strt:end] = test_list[strt:end][::-1]
# printing result
print("Range reversed range list : " + str(test_list))
输出:
The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]
Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]