+ 4
I want to code a function which return an integer list in ascending order keeping 0s fixed in their position. Can anyone help?
For example: input [5,0,0,3,4,9,0] will return [3,0,0,4,5,9,0]
4 Respostas
+ 3
Hi, try this:
def sortCero(lista):
"""
return an integer list in ascending
order keeping 0s fixed in their position
||ispovala||
"""
indicesCero=[]
for i in range(len(lista)):
if lista[i]==0:
indicesCero.append(i)
while 0 in lista:
lista.remove(0)
lista.sort()
for s in indicesCero:
lista.insert(s,0)
return lista
I hope I've helped
+ 2
a=[2,4,6,7,4,4,8,6,7,4,9,0,1,2,5,3,7,5,2,4,9,7,0,3,1,5,8,4]
e=[]#empty list
b=a[:]# copied a to b
b.sort()#sort the b
for i in range(len(a)):#find the index position of all four
if a[i]==4:
e.append(i)
else: continue
for j in range(b.count(4)):#remove all four
b.remove(4)
for k in e:#insert all fours at the index position
b.insert(k,4)
print(b)
I make this program for 4 you can try with 0 also
+ 2
Thank you both
0
def myfunct(mylist):
mynums = sorted([x for x in mylist if x != 0])
i = 0
for x in range(len(mylist)):
if mylist[x] != 0:
mylist[x] = mynums[i]
i += 1
return mylist
original = [5, 0, 0, 3, 4, 9, 0]
print(myfunct(original))