簡體   English   中英

如何在 Python 的 for 循環中更改列表元素的位置

[英]How to change list elements positions in a for loop in Python

我對編程還很陌生,我真的陷入了一個問題。

假設我有以下列表:

a = [2, "**", 2, "@"]

該列表可能包含更多元素。

我需要做的是改變“**”和“@”之間的位置,所以我會有

a = [2, "@", 2, "**"]

我一直在嘗試使用 for 循環,使用元素索引來執行更改,但列表索引超出范圍。

我怎么能做到?

這是我的代碼:

for j in range (len(expression)):
    if expression[j] == "**":
        if expression[j+2] == "@":
            expression[j], expression[j+2] = expression[j+2], expression[j]
print(expression)

我在答案中的評論(雖然很簡單 tbf)

>>> expression = [2, "**", 2, "@", "**"]
>>> for j in range (len(expression)):
...     if expression[j] == "**":
...         if (
...             len(expression) > j +2 
...             and expression[j+2] == "@"
...         ):
...             expression[j], expression[j+2] = expression[j+2], expression[j]
... 
>>> print(expression)
[2, '@', 2, '**', '**']

說明:如果當前值為**您正在嘗試訪問j+2 但是,您的列表可能沒有該索引(例如,如果**是最后一個元素呢?)。 為了適應這種情況,我將您的if語句擴展為首先檢查長度,然后檢查j+2值。 如果/當第一個檢查/條件失敗時,將跳過(未檢查)第二個條件,因此不會發生 IndexError。

(更新了輸入列表以顯示即使列表末尾的**不會引發錯誤)

試試下面的

# assuming "**" and "@" apper once in the list
a = [2, "**", 2, "@"]
idx_1 = a.index("**")
idx_2 = a.index("@")
# I need to change if and only if ** and @ are separated by another element
if abs(idx_1 - idx_2) > 1:
  del a[idx_1]
  a.insert(idx_1,"@")
  del a[idx_2]  
  a.insert(idx_2,"**")
print(a)

我想過從列表中取出職位,然后交換它們。

for idx , j in enumerate(a):
    if (j == "**"):
        pos1 = idx
    elif (j=="@"):
        pos2 = idx
    
a[pos1],a[pos2] = a[pos2],a[pos1]

暫無
暫無

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

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