簡體   English   中英

有沒有一種方法可以旋轉列表中的值,但列表中的每個第3個位置都是固定的?

[英]Is there a way to rotate values in a list but every 3rd position on the list is stationary?

為了做一些家庭作業,我的老師決定給我們一個編碼挑戰,她自己無法解決。 面臨的挑戰是,給定列表[1、2、3、4、5、6、7、8、9、10、11、12]沿列表每隔第二個值旋轉一次,同時使每個第3個值保持不變。

下面是我嘗試使用的代碼,但它僅使位置0處的值保持不變,而我需要將值保持在位置[0、2、4、6、8、10]

rotation = list(teams)       # copy the list
random.shuffle(rotation)

fixtures = []
for i in range(0, len(teams)-1):
    fixtures.append(rotation)
    rotation = [rotation[0]] + [rotation[-1]] + rotation[1:-1]

預期結果應該是列表的第一次迭代應返回[1、12、3、2、5、4、7、6、9、8、11、10],而第二次迭代應返回[1、10, 3、12、5、2、7、4、9、6、11、8]

如果分成子任務,那么

import itertools

def func(array):
    const_part = array[::2] # get constant part 
    ch_part = array[1::2] # get changing part
    ch_part = ch_part[-1:] + ch_part[:-1] # items shift in changing part
    return list(itertools.chain.from_iterable(zip(const_part,ch_part))) # construct list back
def rotate(x):
    y = x[:]
    for i, v in enumerate(x[:-1]): 
        if str(i/2)[-1] == '0':
            x[i+1] = y[i-1] 
    return x 
x =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 
print(rotate(x)) #[1, 12, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]
print(rotate(x)) #[1, 10, 3, 12, 5, 2, 7, 4, 9, 6, 11, 8]

從您的預期輸出中,您需要保留列表的每個第二元素,可以通過[::2]進行提取:

rotate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
rotate[::2]
#[1, 3, 5, 7, 9, 11]

其他需要改組的元素可以通過[1::2]提取:

rotate[1::2]
#[2, 4, 6, 8, 10, 12] 

現在,您只需要將第二個列表的最后一個元素移到頂部。 有很多方法可以做到,但是我很懶,並且使用以下方法:

result = [rotate[1::2].pop(-1)] + rotate[1::2][:-1]

然后,您可以將修改后的列表一起加入:

r = [(a,b) for a,b in zip(rotate[::2],result)]
r = [x for i in r for x in i]
r
#[1, 12, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM