我想反轉一個串列,但只有索引是偶數的。所以我的目標是一個開始的串列:
A = [1,2,3,4,5]
應該看起來像:
B = [5,2,3,4,1]
因此,要檢查索引的位置,我什至會寫:
for j in range(0,len(A)):
if j % 2 == 0:
print(A[j]) #prints all the values at equal indexes.
我將如何僅在 B 滿足上述條件的情況下反轉 A?所以為了解釋更多,我希望陣列 A 的索引交換它們的位置。偶數索引是: 0 , 2 , 4 其中 A 的值為 1 , 3 , 5 。我希望這些值切換到 5,3,1,但甚至不應該保持不變的索引。
有沒有像這樣的快速方法:
A[::-1]
uj5u.com熱心網友回復:
Michael Szczesny 等其他人提出了更簡潔的解決方案,例如:
A[::2] = reversed(A[::2])
已經在評論中,但這里有一個更詳細的內容,以防它幫助您了解正在發生的事情。
我們假設開始的串列已經排序。
A = [1,2,3,4,5]
#We isolate the even indices
even_indices = []
for i in range(len(A)):
if i%2==0:
even_indices.append(A[i])
#We reverse the even indices
even_indices = list(reversed(even_indices))
print(even_indices)
B = []
#We put everything back together, if the index is odd, we use the value from A, if not, we use the value from even_indices, which has been reversed.
for i in range(len(A)):
if i%2==1:
B.append(A[i])
else:
B.append(even_indices[i//2])
print(B)
輸出:
[5, 3, 1]
[5, 2, 3, 4, 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407307.html
標籤:
