在遍历时修改列表 [英] Modifying a list while traversing it
本文介绍了在遍历时修改列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以在迭代时修改列表.我应该通过在项目之间应用一些操作来生成列表,在遍历列表时更新列表l
应该更简单.
Is there a way to modify a list while iterating it. I should generate a list by applying some operations between items, it should be more simple to update the list l
while traversing it.
在python或itertools中是否有任何隐藏功能可用于将其作为一行代码.
Is there any hiding feature in python or itertools that I can use to make this as one line code.
以这个简单的例子.
l=[1,2,3,4,5]
a=[0]
for i,item in enumerate(l):
a+=[item**2-a[-1]]
l+=a
print l
应该是这样的:
for i,item in enumerate(l):
# Update List L
print l
推荐答案
您可以改为遍历列表的副本,然后修改原始副本:
You can iterate over a copy of the list instead, and modify the original:
print mylist
# [0, 1, 2, 3, 4, 5]
for item in mylist[:]:
mylist.append(item**2)
print mylist
# [0, 1, 2, 3, 4, 5, 0, 1, 4, 9, 16, 25]
这篇关于在遍历时修改列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文