Modifying a list while traversing it

核能气质少年 提交于 2019-12-12 05:48:19

问题


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.

Is there any hiding feature in python or itertools that I can use to make this as one line code.

Taking this quick example.

l=[1,2,3,4,5]
a=[0]
for i,item in enumerate(l):
    a+=[item**2-a[-1]]
l+=a
print l

It should be something like:

 for i,item in enumerate(l):
    # Update List L
    print l

回答1:


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]



回答2:


If you add/append to the list, the loop will continue over the added items.

>>> L = [1]
>>> for i, j in enumerate(L):
...     L.append(i + j)
...     if L[-1] > 20:
...         break
... 
>>> L
[1, 1, 2, 4, 7, 11, 16, 22]

The tricky part in your example is stopping at the end of the original list

L = [1,2,3,4,5]
L.append(0)
for i in range(len(L) - 1):
    L += [L[i] ** 2 - L[-1]]

print L

Seems a little contrived, but perhaps there's a cleaner way if you can tell us your real use case




回答3:


You can get a length of your list at the start to avoid infinite loop when you add to the same list

l=[1,2,3,4,5]
item=0

for i in xrange(len(l)):
    l.append(l[i]**2-item)
    item=l[-1]

print l

#[1, 2, 3, 4, 5, 1, 3, 6, 10, 15]


来源:https://stackoverflow.com/questions/26899872/modifying-a-list-while-traversing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!