简体   繁体   English

如何替换列表中的元素?

[英]How do I replace elements in a list?

I am trying to write a loop that replaces all the elements of the list with elements that are half a big.我正在尝试编写一个循环,用半个大的元素替换列表中的所有元素。 If the list is [1,2,3,4] the new list should read [0.5,1,1.5,2].如果列表为 [1,2,3,4],则新列表应为 [0.5,1,1.5,2]。 WITHOUT CREATING A NEW LIST!无需创建新列表!

I tried the following我尝试了以下

for i in Glist:
    i = Glist[i]/2
    Glist.append(i)

And hot an error : list index out of range how to stop the loop?和热错误:列表索引超出范围如何停止循环?

also tried this:也试过这个:

for i in mylist:
    i = i/2
    mylist.append(i)

did not work不工作

If you want to replace elements of a list, then the length of the list should not change, which append does.如果要替换列表的元素,则列表的长度不应更改,而append会更改。 Instead:反而:

for i,v in enumerate(Glist):
    Glist[i] = v/2.0

Note that iterating over a list while appending to it is a perfect recipe for an endless loop .请注意,在追加到列表的同时对其进行迭代是无限循环的完美方法。 Besides iiuc you want to modify the actual elements, here you're just appending to the end of the list.除了 iiuc 你想修改实际元素,这里你只是附加到列表的末尾。

You could use a regular for loop and just modify in-place with:您可以使用常规的 for 循环,只需在原地修改:

for i in range(len(Glist)):
    Glist[i] /= 2.

print(Glist)
[0.5, 1.0, 1.5, 2.0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM