![](/img/trans.png)
[英]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
[英]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.