Python|轮换列表的方法
列表的轮换也已经在前面讨论过,但是这篇特别的文章侧重于速记和各种简短的技术,以在单行或一个单词中实现这一点。这个操作在程序员的生活中完成各种任务是非常必要的。
让我们讨论旋转列表的不同方法。
方法#1:使用切片
这种特定方法是通用方法,主要用于完成此任务,并且也在许多文章中进行了讨论。它的工作原理是将后面的切片部分连接到给定旋转数的初始切片部分。
# Python3 code to demonstrate
# rotation of list
# using slice
# initializing list
test_list = [1, 4, 6, 7, 2]
# printing original list
print ("Original list : " + str(test_list))
# using slicing to left rotate by 3
test_list = test_list[3:] + test_list[:3]
# Printing list after left rotate
print ("List after left rotate by 3 : " + str(test_list))
# using slicing to right rotate by 3
# back to Original
test_list = test_list[-3:] + test_list[:-3]
# Printing after right rotate
print ("List after right rotate by 3(back to original) : "
+ str(test_list))
输出:
Original list : [1, 4, 6, 7, 2]
List after left rotate by 3 : [7, 2, 1, 4, 6]
List after right rotate by 3 ( back to original) : [1, 4, 6, 7, 2]
方法#2:使用列表理解
这个问题也可以通过简单的方法来解决,但它的更短的实现将在列表理解的帮助下。在这种方法中,我们只是将每个值的索引重新分配到旋转后的特定位置。
# Python3 code to demonstrate
# rotation of list
# using list comprehension
# initializing list
test_list = [1, 4, 6, 7, 2]
# printing original list
print ("Original list : " + str(test_list))
# using list comprehension to left rotate by 3
test_list = [test_list[(i + 3) % len(test_list)]
for i, x in enumerate(test_list)]
# Printing list after left rotate
print ("List after left rotate by 3 : " + str(test_list))
# using list comprehension to right rotate by 3
# back to Original
test_list = [test_list[(i - 3) % len(test_list)]
for i, x in enumerate(test_list)]
# Printing after right rotate
print ("List after right rotate by 3(back to original) : "
+ str(test_list))
输出:
Original list : [1, 4, 6, 7, 2]
List after left rotate by 3 : [7, 2, 1, 4, 6]
List after right rotate by 3(back to original) : [1, 4, 6, 7, 2]
方法 #3:使用collections.deque.rotate()
collections 模块有提供rotate()
的 deque 类,它是允许旋转的内置函数。这是鲜为人知的函数,但具有更大的实用性。
# Python3 code to demonstrate
# rotation of list
# using rotate()
from collections import deque
# initializing list
test_list = [1, 4, 6, 7, 2]
# printing original list
print ("Original list : " + str(test_list))
# using rotate() to left rotate by 3
test_list = deque(test_list)
test_list.rotate(-3)
test_list = list(test_list)
# Printing list after left rotate
print ("List after left rotate by 3 : " + str(test_list))
# using rotate() to right rotate by 3
# back to Original
test_list = deque(test_list)
test_list.rotate(3)
test_list = list(test_list)
# Printing after right rotate
print ("List after right rotate by 3(back to original) : "
+ str(test_list))
输出:
Original list : [1, 4, 6, 7, 2]
List after left rotate by 3 : [7, 2, 1, 4, 6]
List after right rotate by 3(back to original) : [1, 4, 6, 7, 2]