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

3 ways to circularly shift Python sequences

不言
不言Original
2018-04-09 15:03:134767browse

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 (k7735d9a1cf2007d68ddece5f76fcbf650) 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

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!

Statement:
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