[英]Single list rotation of the first half with the other half, including odd number of elements
l = [4,5,7,9,10,12]
def rotation(l,n):
return l[n:] + l[:n]
print rotation(l,3)
Let "l" be the above mentioned list, with the above code I am able to rotate the first half [4,5,7] with the other half [9,10,12], getting the desired output [9, 10, 12, 4, 5, 7]. 令“ l”为上述列表,使用上述代码,我可以将前半部分[4,5,7]与另一半部分[9,10,12]旋转,得到所需的输出[9,10, 12、4、5、7]。 However what I am trying to do and I cannot figure out, is in the case when we have an odd number of elements.
但是,当元素数量奇数时,我想做的却无法弄清楚。 Let's say l = [4,5,7,8,9,10,12] I want the odd number that is in the middle, in this case [8], to remain in the middle, and the first half to rotate with the last half, getting the output in this case [9,10,12,8,4,5,7]
假设l = [4,5,7,8,9,10,12]我希望中间的奇数(在这种情况下为[8])保留在中间,并且上半部分与最后一半,在这种情况下获取输出[9,10,12,8,4,5,7]
Thanks in advance. 提前致谢。
If I get the point, this could work. 如果我明白这一点,那可能行得通。
But I don't see the need to pass the second parameter to the method (unless you are looking for something different). 但是我看不到需要将第二个参数传递给方法(除非您正在寻找不同的东西)。
def rotation(l):
size = len(l)
n = size // 2
res = l[-n:] + l[:n] if size % 2 == 0 else l[-n:] + [l[n]] + l[:n]
return res
print(rotation([4,5,7,8,9,10])) #=> [8, 9, 10, 4, 5, 7]
print(rotation([4,5,7,8,9,10,12])) #=> [9, 10, 12, 8, 4, 5, 7]
def rotation(l,n):
if len(l) % 2 == 0:
return l[n:] + l[:n]
else:
return l[-n:] + [l[n]] + l[:n]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.