将列表中的元素向左旋转一个位置 [英] rotate elements in a list by a one position to the left

查看:98
本文介绍了将列表中的元素向左旋转一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求编写一个函数rotate_left3(nums),该函数采用长度3 的整数list称为nums,并返回带有元素向左旋转"的list,因此[1、2、3]产生[2、3、1].

I'm asked to write a function rotate_left3(nums) that takes a list of ints of length 3 called nums and returns a list with the elements "rotated left" so [1, 2, 3] yields [2, 3, 1].

问题要求轮换长度为3的列表,.我可以通过以下功能轻松地做到这一点(只要列表的长度仅为3):

The questions asks to rotate lists of length 3 only. I can easily do this by the following function (as long as the lists will only be of length 3):

def  rotate_left3(nums):
    return [nums[1]] + [nums[2]] + [nums[0]]

但是,我的问题是,如何对长度未知的列表执行相同的操作?

However, my question is, how do I do the same operation but with lists of unknown lengths?

作为初学者,我已经看到了一些复杂的解决方案.因此,如果能使解决方案尽可能简单,我将不胜感激.

推荐答案

让我们创建一个列表:

>>> nums = range(5)

现在,让我们向左旋转一个位置:

Now, let's rotate left by one position:

>>> nums[1:] + nums[:1]
[1, 2, 3, 4, 0]

如果我们想向左旋转两个位置,可以使用:

If we wanted to rotate left by two positions, we would use:

>>> nums[2:] + nums[:2]
[2, 3, 4, 0, 1]

这篇关于将列表中的元素向左旋转一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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