简体   繁体   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)

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.

相关问题 如果列表中的元素数大于 2,则将列表前半部分中的 n 个元素与列表另一半中的元素组合 - Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2 如何有效地检查列表的前半部分是否与另一部分相等? - How to check if the first half of a list is equal to the other efficiently? 我怎样才能给这个列表的前半部分一个 A,给后半部分一个 B? - How can I give an A to first half of this list and a B to the second half? 获取列表中所有重复元素的一半 - get half of all repeating elements in a list 将列表移至其他列表一半大小以获取公共元素 - Moving a list half its size against other list to get the common elements 找到列表中元素总和减半的最小步骤数,其中每个步骤将列表中的项目减半 O(N) - Find the minimum number of steps to half the sum of elements in a list where each step halves an item in the list in O(N) 半数金字塔Python - Number half Pyramid Python 汇总列表中所有元素但不包括第一个偶数的函数 - Function That Sums All Elements in List Up to But Not Including The First Even Number Python 检查列表中至少一半元素是否为元组的程序 - Python program that checks if at least half of the elements in a list are tuples 为什么python在tkinter中只显示列表的前半部分? - Why does python only shows the first half of the list in tkinter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM