use*_*008 11 python iterator loops list python-datamodel
在Java中我可以通过使用a Iterator然后使用.remove()迭代器的方法来删除迭代器返回的最后一个元素,如下所示:
import java.util.*;
public class ConcurrentMod {
public static void main(String[] args) {
List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
String color = it.next();
System.out.println(color);
if (color.equals("green"))
it.remove();
}
System.out.println("At the end, colors = " + colors);
}
}
/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/
Run Code Online (Sandbox Code Playgroud)
我将如何在Python中执行此操作?我在for循环中迭代它时无法修改列表,因为它会导致跳过东西(参见此处).并且似乎没有相当于IteratorJava 的接口.
Ale*_*lli 28
Python中的最佳方法是创建一个新列表,理想情况是在listcomp中,将其设置为[:]旧列表,例如:
colors[:] = [c for c in colors if c != 'green']
Run Code Online (Sandbox Code Playgroud)
不要colors =为一些答案可能暗示-只有重新绑定名字,并最终离开旧的"身体"晃来晃去一些参考; colors[:] =在所有方面都好多了;-).
Ark*_*ady 19
迭代列表的副本:
for c in colors[:]:
if c == 'green':
colors.remove(c)
Run Code Online (Sandbox Code Playgroud)
您可以使用过滤功能:
>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>
Run Code Online (Sandbox Code Playgroud)