繁体   English   中英

前一半与后一半的单列表轮换,包括奇数个元素

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM