首页 > 解决方案 > 知道为什么 python3 不将 False 视为布尔值吗?

问题描述

知道为什么 python3 不将 False 视为布尔值吗?我想将所有零移动到列表的末尾。

def move_zeros(array):

    for i in array:
        if type(i) is not bool:
            if i == 0:
                array.append(int(i)) # catching non bool values that are zeros, adding at the end of the list
                array.remove(i) # removing original
        elif type(i) is bool:
            pass #Here it catches False from the input, it should do nothing but somehow it is moved to the end of the list as zero in the output.

    return array


print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
                  False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))

输出:

['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

标签: python-3.xboolean

解决方案


尝试对您的代码稍作修改:

def move_zeros(array):
    new_list = []   # Work a new list
    for i in array:
        print(f"I = {i}")
        if type(i) is not bool:
            if i == 0:
                new_list.append(int(i))
        else:
            pass

    return new_list


print(move_zeros(["a", 0, 0, "b", None, "c", "d", 0, 1,
                  False, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]))

推荐阅读