Dre*_*kes 77 python list rotation
可能重复:
在python中移动列表的有效方法
我想将Python列表向右或向左旋转任意数量的项目(后者使用否定参数).
像这样的东西:
>>> l = [1,2,3,4]
>>> l.rotate(0)
[1,2,3,4]
>>> l.rotate(1)
[4,1,2,3]
>>> l.rotate(-1)
[2,3,4,1]
>>> l.rotate(4)
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
怎么可能这样做?
YXD*_*YXD 151
def rotate(l, n):
return l[-n:] + l[:-n]
Run Code Online (Sandbox Code Playgroud)
更传统的方向:
def rotate(l, n):
return l[n:] + l[:n]
Run Code Online (Sandbox Code Playgroud)
例:
example_list = [1, 2, 3, 4, 5]
rotate(example_list, 2)
# [3, 4, 5, 1, 2]
Run Code Online (Sandbox Code Playgroud)
参数rotate是一个列表和一个表示移位的整数.该函数使用切片创建两个新列表,并返回这些列表的连接.该rotate功能不会修改输入列表.
tom*_*asz 96
如果适用,您可以将其collections.deque用作解决方案:
import collections
d = collections.deque([1,2,3,4,5])
d.rotate(3)
print d
>>> deque([3, 4, 5, 1, 2])
Run Code Online (Sandbox Code Playgroud)
作为奖励,我希望它比内置列表更快.
Aar*_*our 22
以下函数将旋转列表l,x右侧空格:
def rotate(l, x):
return l[-x:] + l[:-x]
Run Code Online (Sandbox Code Playgroud)
请注意,如果x超出范围,这将仅返回原始列表[-len(l), len(l)].要使其适用于所有值x,请使用:
def rotate(li, x):
return li[-x % len(li):] + li[:-x % len(li)]
Run Code Online (Sandbox Code Playgroud)
>>> l=[1,2,3,4]
>>> l[1:]+l[:1]
[2, 3, 4, 1]
>>> l=[1,2,3,4]
>>> l[2:]+l[:2]
[3, 4, 1, 2]
>>> l[-1:]+l[:-1]
[4, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
一般将n向左旋转(在调用中为正y rotate)或向右旋转(负y),然后:
def rotate(l, y=1):
if len(l) == 0:
return l
y = y % len(l) # Why? this works for negative y
return l[y:] + l[:y]
Run Code Online (Sandbox Code Playgroud)
如果您希望旋转方向与示例相同,则只需y在旋转时取消.
def rotate(l, y=1):
if len(l) == 0:
return l
y = -y % len(l) # flip rotation direction
return l[y:] + l[:y]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130952 次 |
| 最近记录: |