ลิสต์เป็นคอนเทนเนอร์สำคัญ ใช้ในทุกโค้ด การหมุนลิสต์ (Rotate) มีหลายวิธี
1. Slicing (เร็วที่สุด, อ่านง่าย)
test_list = [1, 4, 6, 7, 2] # Left rotate by 3 test_list = test_list[3:] + test_list[:3] # [7, 2, 1, 4, 6] # Right rotate by 3 (กลับสู่เดิม) test_list = test_list[-3:] + test_list[:-3] # [1, 4, 6, 7, 2]
2. List Comprehension
test_list = [1, 4, 6, 7, 2] # Left rotate by 3 test_list = [test_list[(i + 3) % len(test_list)] for i, _ in enumerate(test_list)] # Right rotate by 3 test_list = [test_list[(i - 3) % len(test_list)] for i, _ in enumerate(test_list)]
3. collections.deque.rotate() (เหมาะสำหรับการหมุนบ่อย)
from collections import deque test_list = [1, 4, 6, 7, 2] dq = deque(test_list) dq.rotate(-3) # Left rotate test_list = list(dq) dq = deque(test_list) dq.rotate(3) # Right rotate test_list = list(dq)
สรุป
- Slicing เร็วที่สุด สั้นที่สุด เหมาะสำหรับครั้งเดียว
- deque.rotate() O(1) เหมาะสำหรับหมุนหลายครั้งติดต่อกัน
- List comprehension เข้าใจง่าย แต่ช้ากว่า slicing