我的for循环不是';是否根据条件删除阵列中的项目?python
我有一个数组(移动)的数组。我想遍历moves数组,并为每个元素设置一个条件。条件是,如果元素中的任何一个数字都是负数,那么我想从moves数组中删除该元素。循环无法正确删除我的项目。但是如果我在完全相同的循环中运行它两次,那么它将删除最后一个元素。这对我来说毫无意义。使用Python 3.6我的for循环不是';是否根据条件删除阵列中的项目?python,python,python-3.x,Python,Python 3.x,我有一个数组(移动)的数组。我想遍历moves数组,并为每个元素设置一个条件。条件是,如果元素中的任何一个数字都是负数,那么我想从moves数组中删除该元素。循环无法正确删除我的项目。但是如果我在完全相同的循环中运行它两次,那么它将删除最后一个元素。这对我来说毫无意义。使用Python 3.6 moves = [[3,-1],[4,-1],[5,-1]] for move in moves: if move[0] < 0 or move[1] < 0: mov
moves = [[3,-1],[4,-1],[5,-1]]
for move in moves:
if move[0] < 0 or move[1] < 0:
moves.remove(move)
有什么想法吗?不要同时重复和修改 您可以使用列表comp或
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]]
filter()
和all()
的Doku可以在上的概述中找到。您可以遍历列表的副本。这可以通过在for循环列表中添加[:]
来完成
输入
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)
[]
不要同时迭代和修改您迭代的列表。那么,如何根据条件筛选列表?在第二个示例中,没有任何内容是有效的,因为所有元素的内部元素均小于2。。您想做什么?Yoiur第一个示例也不会有任何剩余内容-因为所有元素都包含少于1个元素0@PatrickArtner是的,我知道这是应该发生的,但正如你从输出中看到的,这不是正在发生的事情。这就是问题所在:)
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)
[]