简体   繁体   中英

Global and local scope variables in Python; Delete item inside from array inside the loop

This is the code:

def deleteObj(array):
    for i in range (0, len(array)):
        if array[i]:
            if type(array[i]) == int or type(array[i]) == float:
                if int(array[i]) == 0:
                    del array[i]
        elif not array[i]:
            break

    print(array)

So, at the end it prints me whole array without changes. I've broke my mind already xDxDxD
PS I can't make array a global variable before posting inside function

You have two problems:

  1. if array[i]: will be false when array[i] is None , but also when it is 0 .
  2. You are removing from array while iterating on it, it will cause iterating list index out of range

You need to check if the item is None explicitly, and use remove on a copy of array so you can remove items. You can also skip the checks for int or float and the casting to int , they are not necessary

def deleteObj(array):
    for item in list(array):
        if item is not None:
            if item == 0:
                array.remove(item)
        else:
            break

    print(array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM