The following is a recommendation for three methods of circular shifting of Python sequences. It has a good reference value and I hope it will be helpful to everyone.
The first method: The characteristic is that it is direct and easy to understand. The disadvantage is that it is slow and can only achieve circular left shift.
def demo(lst, k): temp = lst[:] for i in range(k): temp.append(temp.pop(0)) return temp
The second method: is characterized by fast speed and adaptive circular left shift (k> 0) and right shift (k<0), the disadvantage is that it involves algorithms and is not easy to understand.
def demo(lst, k): x = lst[:k] x.reverse() y = lst[k:] y.reverse() r = x+y return list(reversed(r))
The most Pythonic ultimate method: Use slices, simple and easy to understand, fastest, and can be used simultaneously Implement circular left shift (k>0) and right shift (k<0).
def demo(lst, k): return lst[k:] + lst[:k]
Related recommendations:
Python method to generate random numbers with any range and any precision
The above is the detailed content of 3 ways to circularly shift Python sequences. For more information, please follow other related articles on the PHP Chinese website!