Move all 0s in the list to the back, the order of non-zero elements does not change, and it is required to be performed on the original list.

#Move all 0s in the list to the back, the order of non-zero elements does not change, and it is required to be performed on the original list. 

lst1 = [0, 0, 0, 0, 18754, 0, 0, 0, 0, 0, 0 , 13, 1, 0, 1, 5, 0, 6, 0, 1, 9, 1, 2, 3, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

length = len(lst1)

for k in range(length):
for i in range(length-1):
if lst1[i] == 0:
lst1[i], lst1[i+1] = lst1[i+ 1], lst1[i]

print(lst1)

#[18754, 13, 1, 1, 5, 6, 1, 9, 1, 2, 3, 7, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324839668&siteId=291194637