簡體   English   中英

Python pop 和 append 沒有將列表 1 中的所有元素移動到列表 2

[英]Python pop and append are not moving all elems in list1 to list 2

為什么 pop 和 append 沒有完成整個循環? 我的第一個猜測是 pop 沒有重新調整原始列表的索引,但是當我 print(txt[0]) 確認它仍然在前面時,這似乎不是真的。 我試圖弄清楚為什么下面不起作用。 謝謝你。

txt = 'shOrtCAKE'
txt = list(txt)
new_list = []

for x in txt:
    value = txt.pop(0)
    new_list.append(value)

print(new_list)
print(txt)
print(txt[0])

迭代列表時不應修改列表。 而是使用此代碼

for x in txt:
    value = x
    new_list.append(value)
txt = [] # assuming you want txt to be empty for some reason

但是,如果您最終打印txt[0] ,您將得到錯誤,因為列表索引將超出范圍

但是,您實際上並不需要循環。 只需執行以下操作:

new_list = txt[:] # [:] ensures that any changes done to txt won't reflect in new_list

您不應該從您正在迭代的列表中刪除元素。 在這種情況下,您甚至沒有使用迭代期間獲得的列表的值。

如果您仍想使用pop ,則有多種可能性,其中涉及迭代txt 例如:

  • 循環固定次數( len(txt)在開始時計算):
for _ in range(len(txt)):
    new_list.append(txt.pop(0))
  • txt不為空時循環:
while txt:
    new_list.append(txt.pop(0))
  • 循環直到pop失敗:
while True:
    try:
        new_list.append(txt.pop(0))
    except IndexError:
        break

當然,您不必使用pop 例如,您可以這樣做:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list

暫無
暫無

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

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