python-3.x - 知道为什么 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]
解决方案
尝试对您的代码稍作修改:
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]))
推荐阅读
- sql - SQL 返回最后一个空格右边的字符
- amazon-web-services - 模型 dynamodb 表?
- php - 用 foreach 循环上标签内的字符串替换特定值
- python - Django,获取 ChoiceField 表单的值
- c++ - Qt 示例无法在 Ubuntu 上运行
- python - 如何使用 SQLAlchemy 加入 generate_series
- python - sqlalchemy 使用中间表加入自我(工作 sql,而不是 sqlalchemy)
- c++ - 是否可以在 c++ 中使用单个变量将不同的数据类型作为输入
- sql - 如何避免多次加入同一个表
- ios - 如何在 App Store Connect 中更新其他人的 iOS TestFlight 版本?