Python 3.6 与 Python 3.8.2 if 语句 'is' - 显示不同的结果
Python 3.6 vs Python 3.8.2 if statement with 'is' - shows different results
我有这个问题,我需要将每个 0 或 0.0 放在列表的后面,同时保存其他元素的顺序,例如:
move_zero([1,3,4,[],False,None,0,0,3,0.0,4])
将输出:
[1,3,4,[],False,None,3,4,0,0,0]
注意函数特别是从0.0变成0没问题,这就是它应该做的
现在,这是我对这个问题的看法:
def move_zeros(array):
new_arr = []
count_zero = 0
for x in array:
if (x is 0) or (x is 0.0):
count_zero += 1
else:
new_arr.append(x)
return new_arr + count_zero * [0]
但是由于某种我不能称为原因的原因,它没有进入我输入的第一个 if 语句:
[9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]
输出为:
[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]
它在 Python 3.6 上输出了错误的列表
在 python 3.8.2 上它工作正常..(但是我需要为此使用 3.6)
我哪里错了? if 语句似乎没问题!
谢谢!
试试这个
def move_zeros(a):
res = []
x = 0
for num in a:
if str(num) == '0.0' or str(num) == '0':
x += 1
else:
res.append(num)
return res + [0] * x
print(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]))
输出:
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
But for some reason which I cannot call why, it does not enter the first if statement where my input is:
您需要使用 ==
来比较值。 is
用于比较Python中的同一性。有关 ==
与 Python 中的 is
的信息,请参阅 this。
试试这个:
def move_zeros(a):
r = [i for i in a if not isinstance(i, (float, int)) or str(i) not in ('0.0', '0')]
r += [0] * (len(a) - len(r))
return r
print(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]))
输出:
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
我有这个问题,我需要将每个 0 或 0.0 放在列表的后面,同时保存其他元素的顺序,例如:
move_zero([1,3,4,[],False,None,0,0,3,0.0,4])
将输出:
[1,3,4,[],False,None,3,4,0,0,0]
注意函数特别是从0.0变成0没问题,这就是它应该做的
现在,这是我对这个问题的看法:
def move_zeros(array):
new_arr = []
count_zero = 0
for x in array:
if (x is 0) or (x is 0.0):
count_zero += 1
else:
new_arr.append(x)
return new_arr + count_zero * [0]
但是由于某种我不能称为原因的原因,它没有进入我输入的第一个 if 语句:
[9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]
输出为:
[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]
它在 Python 3.6 上输出了错误的列表
在 python 3.8.2 上它工作正常..(但是我需要为此使用 3.6)
我哪里错了? if 语句似乎没问题!
谢谢!
试试这个
def move_zeros(a):
res = []
x = 0
for num in a:
if str(num) == '0.0' or str(num) == '0':
x += 1
else:
res.append(num)
return res + [0] * x
print(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]))
输出:
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
But for some reason which I cannot call why, it does not enter the first if statement where my input is:
您需要使用 ==
来比较值。 is
用于比较Python中的同一性。有关 ==
与 Python 中的 is
的信息,请参阅 this。
试试这个:
def move_zeros(a):
r = [i for i in a if not isinstance(i, (float, int)) or str(i) not in ('0.0', '0')]
r += [0] * (len(a) - len(r))
return r
print(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]))
输出:
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]