Примечание о or
:
x == 0 or x == float(0)
работает x in [0, float(0)]
также работает и проще [x for x in array if x != 0]
& [x for x in array if x != float(0)]
можно заменить на [x for x in array if x not in [0, float(0)]]
Упростить функцию
def move_zeros(array):
zc = array.count(0)
array = [x for x in array if x != 0] # removes all zeros
array.extend([0 for _ in range(zc)])
return array
test = [9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]
y = move_zeros(test)
print(y)
>>> [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Проверка y
против test
:
from collections import Counter
print(test.count(0))
>>> 10
print(y.count(0))
>>> 10
print(len(test))
>>> 20
print(len(y))
>>> 20
test_dict = Counter(test)
print(test_dict)
>>> Counter({9: 4, 0.0: 10, 1: 4, 2: 1, 3: 1})
y_dict = Counter(test)
print(y_dict)
>>> Counter({9: 4, 0.0: 10, 1: 4, 2: 1, 3: 1})
В качестве альтернативы:
test = [9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]
test_sorted = test.sort(reverse=True)
print(test_sorted)
>>> [9, 9, 9, 9, 3, 2, 1, 1, 1, 1, 0.0, 0, 0, 0, 0.0, 0, 0, 0, 0, 0]