2 回答

TA贡献1827条经验 获得超4个赞
您可以遍历列表的副本。这可以通过添加[:]您的 for 循环列表来完成moves[:]。
输入
moves = [[3,-1],[4,-1],[5,-11], [2,-2]]
for move in moves[:]:
if (move[0] < 0) or (move[1] < 0):
moves.remove(move)
print(moves)
输出
[]

TA贡献1803条经验 获得超6个赞
不要同时迭代和修改。
您可以使用列表合成或filter()获取适合您需要的列表:
moves = [[3,1],[4,-1],[5,1],[3,-1],[4,1],[5,-1],[3,1],[-4,1],[-5,1]]
# keep all values of which all inner values are > 0
f = [x for x in moves if all(e>0 for e in x)]
# same with filter()
k = list(filter(lambda x:all(e>0 for e in x), moves))
# as normal loop
keep = []
for n in moves:
if n[0]>0 and n[1]>0:
keep.append(n)
print(keep)
print(f) # f == k == keep
输出:
[[3, 1], [5, 1], [4, 1], [3, 1]]
Doku for filter()andall()可以在内置函数概述中找到
添加回答
举报