Python 列表轮换 [英] Python list rotation

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

问题描述

<块引用>

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

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

像这样:

<预><代码>>>>l = [1,2,3,4]>>>l.旋转(0)[1,2,3,4]>>>l.旋转(1)[4,1,2,3]>>>l.旋转(-1)[2,3,4,1]>>>l.旋转(4)[1,2,3,4]

如何做到这一点?

解决方案

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

更传统的方向:

def 旋转(l,n):返回 l[n:] + l[:n]

示例:

example_list = [1, 2, 3, 4, 5]旋转(示例列表,2)# [3, 4, 5, 1, 2]

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

Possible Duplicate:
Efficient way to shift a list in 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).

Something like this:

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

How might this be done?

解决方案

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

More conventional direction:

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

Example:

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

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

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天全站免登陆