上半部分与另一半的单列表轮换,包括奇数个元素
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)
让"l"成为上面提到的列表,使用上面的代码我可以将前半部分[4,5,7]与另一半[9,10,12]旋转,得到期望的输出 [9, 10, 12, 4, 5, 7]。但是,当我们有奇数个元素时,我正在尝试做但我无法弄清楚的是。假设 l = [4,5,7,8,9,10,12] 我希望中间的奇数(在本例中为 [8])保留在中间,而前半部分旋转后半部分,在本例中得到输出 [9,10,12,8,4,5,7]
提前致谢。
如果我明白了,这可以工作。
但我认为不需要将第二个参数传递给该方法(除非您正在寻找不同的东西)。
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]
l = [4,5,7,9,10,12]
def rotation(l,n):
return l[n:] + l[:n]
print rotation(l,3)
让"l"成为上面提到的列表,使用上面的代码我可以将前半部分[4,5,7]与另一半[9,10,12]旋转,得到期望的输出 [9, 10, 12, 4, 5, 7]。但是,当我们有奇数个元素时,我正在尝试做但我无法弄清楚的是。假设 l = [4,5,7,8,9,10,12] 我希望中间的奇数(在本例中为 [8])保留在中间,而前半部分旋转后半部分,在本例中得到输出 [9,10,12,8,4,5,7]
提前致谢。
如果我明白了,这可以工作。
但我认为不需要将第二个参数传递给该方法(除非您正在寻找不同的东西)。
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]