+ 3
Sorting of integers list in ascending order and adding all zeros at the end. Is there any best alternative than this?
print("Hello world") list1=[4,0,3,6,1,0,2,0,1] l2=[] def func1(x): if x==0: l2.append(x) list1.sort(key=func1) print(l1) print(l2) list3=list1+l2 print(list3)
8 Antworten
+ 9
Sevda Krithika Sharma , the issue is the function you have defined. The requirements for a function used for key in sorting is:
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.
the function returns some incorrect values = None
May be you should think about an other approuch for your solution.
+ 9
Sevda Krithika Sharma , i would recommend you to do it with a for loop. it's easy to understand.
(1) you need 2 temp lists, one for all the zeros, the other for all numbers except zero
(2) start the for loop by iterating the sorted list1
(3) check each element coming from list1 if it == 0
(4) append it in temp list for zeros
(5) if element is non zero, append it to list for numbers
(6) if iteration on list1 is done, your temp lists contains [0,0,0] and [1, 1, 2, 3, 4, 6]
(7) last step print and concatenate the temp lists to final result
later on you can use this basic version to rework it to a comprehenion. Happy coding!
+ 8
a=[4,0,3,6,1,0,2,0,1]
print([i for i in sorted(a) if i != 0] + [0]*a.count(0))
+ 5
https://code.sololearn.com/ch3VO8074fDd/?ref=app
Just simple.
See now.
+ 4
list2.sort(key = lambda x: max(l) + 1 if x == 0 else x)
+ 3
Sevda Krithika Sharma
One liner 😃😃
print(sorted([x for x in list1 if x]) + [x for x in list1 if not x])
+ 2
Thanks everyone for helping me out.
0
xᴏᴊɪᴀᴋʙᴀʀ I have done in this way...I need other ways