繁体   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