【发布时间】:2020-04-19 08:55:15
【问题描述】:
知道为什么 python3 不将 False 视为 bool 吗? 我想将所有的零移到列表的末尾。
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]
【问题讨论】:
-
循环时不要从列表中追加和删除。
-
同意,这通常是您应该避免的事情,也可能是您的 False 消失的原因。 Python3 确实将 false 视为布尔值,您可以通过执行
print(type(False))来检查这一点。我会重写代码。计算列表中零的数量,并在循环第一个列表时以所需的形式构造第二个列表。这应该消除在循环遍历列表时修改列表所引入的任何奇怪行为。 -
remove几乎总是错误的工具,即使您在迭代时没有修改列表也是如此。几乎总是,您想要的操作是“在此处删除此元素”,但remove的意思是“删除与==比较等于此对象的第一个元素”。
标签: python-3.x boolean