Home > Backend Development > Python Tutorial > 3 ways to circularly shift Python sequences

3 ways to circularly shift Python sequences

不言
Release: 2018-04-09 15:03:13
Original
4696 people have browsed it

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
Copy after login

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))
Copy after login

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]
Copy after login

Related recommendations:

Python method to generate random numbers with any range and any precision

Python network programming uses select to implement socket full-duplex asynchronous communication function

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template