Hướng dẫn rotate a list python
The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer’s life to achieve various tasks. Let’s discuss different ways we can rotate a list in Python. Show
Nội dung chính
Nội dung chính
Nội dung chính
Nội dung chính
Method 1: Rotate a list using SlicingThis particular method is the generic method and is mostly employed to achieve this task and has also been discussed in many articles as well. It works by just joining the later sliced part to the initial sliced part given the rotation number. Python3
Output: 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] Method 2: Rotate a list using list ComprehensionThis problem can also be solved by the naive method, but its shorter implementation would be with the help of list comprehension. In this method, we just reassign the index to each value to the specific position after rotation. Python3
Output: 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] Method 3: Rotate a list using collections.deque.rotate()The collections module has a deque class that provides the rotate(), which is an inbuilt function to allow rotation. This is a lesser-known function but has a greater utility. Python3
Output: 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] Method 4: Rotate a list using NumpyIn this method, we will use Numpy.roll module to roll the list at a given position, i.e. we are rolling the list at position index 1. Python3
Output: [33 11 4 6 7 8] How do you rotate an element in Python?Rotate a Python list. Using deque rotate() function. The collections. ... . Using numpy.roll() function. If you happen to be using NumPy already, you can use the roll() function that rotates the array elements along a given axis. ... . Using Slicing.. Is there a rotate function in Python?Method #3 : Using collections.deque.rotate() The collections module has deque class which provides the rotate() , which is inbuilt function to allow rotation. How do you rotate a number left in Python?for i in range(0, len(arr)): print(arr[i]), #Rotate the given array by n times toward left. for i in range(0, n): How do you rotate items in a list?To rotate the elements of a list, we can convert it to a deque object and then use the rotate() function. Below are some examples of how to rotate items in a list with the deque rotate() function. If you want to rotate the items multiple times, you just pass the number of times to rotate(). |