Python - 旋转列表的方法
pythonserver side programmingprogramming更新于 2025/9/17 11:56:17
列表是一个重要的容器,几乎用于日常编程以及 Web 开发的所有代码中,使用得越多,掌握它的要求就越高,因此了解其操作是必要的。
示例
# 使用切片
# 初始化列表
test_list = [1, 4, 6, 7, 2]
# 打印原始列表
print ("原始列表:" + str(test_list))
# 使用切片向左旋转 3
test_list = test_list[3:] + test_list[:3]
# 打印向左旋转后的列表
print ("向左旋转 3 后的列表:" + str(test_list))
# 使用切片向右旋转 3
# 返回原始位置
test_list = test_list[-3:] + test_list[:-3]
# 向右旋转后打印
print ("向右旋转 3 后的列表(返回原始位置):" + str(test_list))
# 使用列表推导
# 初始化列表
test_list = [1, 4, 6, 7, 2]
# 打印原始列表
print ("原始列表:" + str(test_list))
# 使用列表推导向左旋转 3
test_list = [test_list[(i + 3) % len(test_list)]
for i, x in enumerate(test_list)]
# 打印左旋转后的列表
print ("左旋转 3 次后的列表:" + str(test_list))
# 使用列表推导式右旋转 3 次
# 返回原始列表
test_list = [test_list[(i - 3) % len(test_list)]
for i, x in enumerate(test_list)]
# 打印右旋转后的列表
print ("右旋转 3 次后的列表(返回原始列表):" + str(test_list))
# 使用 rotate()
from collections import deque
# 初始化列表
test_list = [1, 4, 6, 7, 2]
# 打印原始列表
print ("原始列表:" + str(test_list))
# 使用 rotate() 向左旋转 3
test_list = deque(test_list)
test_list.rotate(-3)
test_list = list(test_list)
# 打印向左旋转后的列表
print ("向左旋转 3 后的列表:" + str(test_list))
# 使用 rotate() 向右旋转 3
# 返回原始位置
test_list = deque(test_list)
test_list.rotate(3)
test_list = list(test_list)
# 右旋转后打印
print ("右旋转 3 后的列表(回到原始位置):" + str(test_list))
输出
原始列表:[1, 4, 6, 7, 2] 左旋转 3 后的列表:[7, 2, 1, 4, 6] 右旋转 3 后的列表(回到原始位置):[1, 4, 6, 7, 2] 原始列表:[1, 4, 6, 7, 2] 左旋转 3 后的列表:[7, 2, 1, 4, 6] 右旋转 3 后的列表(回到原始位置):[1, 4, 6, 7, 2] 原始列表:[1, 4, 6, 7, 2] 左旋转 3 后的列表: [7, 2, 1, 4, 6] 右旋转 3 后列表(回到原始位置):[1, 4, 6, 7, 2]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

