tst*_*tst 10 python iterator loops
我基本上需要的是检查列表的每个元素,如果某些条件适合我想从列表中删除它.
例如,让我们这样说吧
list=['a','b','c','d','e']
Run Code Online (Sandbox Code Playgroud)
我基本上想写(原则上而不是我尝试实现的实际代码)
如果列表中的元素为"b"或"c",请将其从列表中删除,然后执行下一个操作.
但
for s in list:
if s=='b' or s=='c':
list.remove(s)
Run Code Online (Sandbox Code Playgroud)
失败是因为当'b'被移除时,循环取'd'而不是'c'作为下一个元素.那么有没有办法比将元素存储在单独的列表中并在之后删除它们更快?
谢谢.
jsb*_*eno 11
更简单的方法是使用列表的副本 - 可以使用从列表的"从头开始"延伸到"结束"的切片来完成,如下所示:
for s in list[:]:
if s=='b' or s=='c':
list.remove(s)
Run Code Online (Sandbox Code Playgroud)
您已经考虑过这一点,这很简单,可以在您的代码中,除非此列表非常大,并且在代码的关键部分(例如,在动作游戏的主循环中).在这种情况下,我有时会使用以下习语:
to_remove = []
for index, s in enumerate(list):
if s == "b" or s == "c":
to_remove.append(index)
for index in reversed(to_remove):
del list[index]
Run Code Online (Sandbox Code Playgroud)
当然你可以使用while循环:
index = 0
while index < len(list):
if s == "b" or s == "c":
del list[index]
continue
index += 1
Run Code Online (Sandbox Code Playgroud)
最好不要重新发明现有的东西.在这些情况下使用过滤器函数和lambda.它更加pythonic,看起来更干净.
filter(lambda x:x not in ['b','c'],['a','b','c','d','e'])
Run Code Online (Sandbox Code Playgroud)
或者你可以使用列表理解
[x for x in ['a','b','c','d','e'] if x not in ['b','c']]
Run Code Online (Sandbox Code Playgroud)