python - Python3 - sorting a list -
i don't understand why 1 , 5 printed 3 times. (i know use list.sort() method.)
lst = [4,5,5,1,6,1] copy = lst.copy() sort = [] in range(len(lst)): min_ = min(copy) k in copy: if k == min_: sort.append(min_) copy.remove(min_) print(sort)
list.remove() removes first occurrence of value, not such values. result you'll first add both 1 values sort, remove 1 of 2 1 values, add remaining 1 value sort again:
>>> lst = [4,5,5,1,6,1] >>> copy = lst.copy() >>> sort = [] >>> min_ = min(copy) >>> min_ 1 >>> k in copy: ... if k == min_: ... sort.append(min_) ... >>> sort [1, 1] >>> copy.remove(min_) >>> copy [4, 5, 5, 6, 1] >>> min_ = min(copy) >>> min_ 1 >>> k in copy: ... if k == min_: ... sort.append(min_) ... >>> sort [1, 1, 1] you use list comprehension remove values, creating new copy excludes value remove filtering:
copy = [v v in copy if v != min_] this not efficient, of course.
note next problem you'll run you'll have emptied out copy before have completed range(len(lst)) iterations. replace loop while copy: loop instead.
alternatively, add first match of min_ value sort:
for in range(len(lst)): min_ = min(copy) k in copy: if k == min_: sort.append(min_) break copy.remove(min_) the break ends for loop early. of course, don't have loop find minimum value, min() call already did, can drop altogether:
for in range(len(lst)): min_ = min(copy) sort.append(min_) copy.remove(min_)
Comments
Post a Comment