Python列表轮换 [英] Python list rotation

查看:98
本文介绍了Python列表轮换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在python中移动列表的有效方法

Possible Duplicate:
Efficient way to shift a list in python

我想将Python列表向右或向左旋转任意数量的项(后者使用负参数).

I'd like to rotate a Python list by an arbitrary number of items to the right or left (the latter using a negative argument).

类似这样的东西:

>>> 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]

这怎么办?

推荐答案

def rotate(l, n):
    return l[-n:] + l[:-n]

更常规的方向:

def rotate(l, n):
    return l[n:] + l[:n]

示例:

example_list = [1, 2, 3, 4, 5]

rotate(example_list, 2)
# [3, 4, 5, 1, 2]

rotate的参数是一个列表和一个表示移位的整数.该函数使用切片创建两个新列表,并返回这些列表的串联. rotate函数不会修改输入列表.

The arguments to rotate are a list and an integer denoting the shift. The function creates two new lists using slicing and returns the concatenatenation of these lists. The rotate function does not modify the input list.

这篇关于Python列表轮换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆