python数组避坑操作(比如删除数组中的所有0)

一、演示坑

tracks = [0, 0, 0, 1, 1, 1]
for track in tracks:
    if track == 0:
        tracks.remove(track)
print(tracks) # [0, 1, 1, 1]

发现:有一个0没有被删去,why???

二、这次遍历时,带上索引打印

tracks = [0, 0, 0, 1, 1, 1]
for index, track in enumerate(tracks):
    if track == 0:
        tracks.remove(track)
    print(index, track)
'''
会依次打印:
    0 0
    1 0
    2 1
    3 1
'''
print(tracks)  # [0, 1, 1, 1]

发现:数组在remove操作后,遍历时索引依次递增,但是数组长度在减小,取值时在更新后的数组按索引取,因此会跳过一些元素

三、如何实现数组去0操作?

  • 方式一
    tracks = [0, 0, 0, 1, 1, 1]
    for i in range(tracks.count(0)):
        tracks.remove(0)
    print(tracks)  # [1, 1, 1]
  • 方式二
    tracks = [0, 0, 0, 1, 1, 1]
    newTracks = []
    for track in tracks:
        if track != 0:
            newTracks.append(track)
    print(newTracks)  # [1, 1, 1]

    借助了新数组

posted @ 2023-06-11 12:34  eliwang  阅读(220)  评论(0编辑  收藏  举报