将列表中的元素向左旋转一个位置
我被要求编写一个函数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]