我的 for 循环没有根据条件删除数组中的项目?

我有一个数组(移动)数组。我想遍历我的移动数组并为每个元素设置一个条件。条件是,如果元素中的任何一个数字为负,那么我想从移动数组中删除该元素。该循环无法正确移除我的物品。但是如果我在完全相同的循环中运行它两次,那么它将删除最后一个元素。这对我来说毫无意义。使用 Python 3.6


moves = [[3,-1],[4,-1],[5,-1]]

for move in moves:

    if move[0] < 0 or move[1] < 0:

        moves.remove(move)

如果你运行这段代码,移动结束的结果是 [[4,-1]] 但是如果你再次通过完全相同的 for 循环运行这个结果,结果是 []


我还尝试使用更多元素来执行此操作,但由于某种原因,它只是没有抓取某些元素。这是 .remove() 的错误吗?这就是我尝试过的...(在此我尝试检测非负数以查看这是否是问题的一部分,它不是)


moves = [[3,1],[4,1],[5,1],[3,1],[4,1],[5,1],[3,1],[4,1],[5,1]]

    for move in moves:

        if move[0] < 2 or move [1] < 2:

            moves.remove(move)

上面代码的结果是


moves = [[4, 1], [3, 1], [4, 1], [5, 1]]

有任何想法吗???


月关宝盒
浏览 178回答 2
2回答

GCT1015

您可以遍历列表的副本。这可以通过添加[:]您的 for 循环列表来完成moves[:]。输入moves = [[3,-1],[4,-1],[5,-11], [2,-2]]for move in moves[:]:&nbsp; &nbsp; if (move[0] < 0) or (move[1] < 0):&nbsp; &nbsp; &nbsp; &nbsp; moves.remove(move)print(moves)输出[]

慕码人8056858

不要同时迭代和修改。您可以使用列表合成或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 > 0f = [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 loopkeep = []for n in moves:&nbsp; &nbsp; if n[0]>0 and n[1]>0:&nbsp; &nbsp; &nbsp; &nbsp; keep.append(n)print(keep)print(f) # f == k == keep&nbsp;&nbsp;输出:[[3, 1], [5, 1], [4, 1], [3, 1]]Doku for filter()andall()可以在内置函数概述中找到
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python