简体   繁体   中英

Python3 - sorting a list

I don't understand why 1 and 5 are printed three times. (I know I could use the list.sort() method.)

lst = [4,5,5,1,6,1]
copy = lst.copy()
sort = []
for i in range(len(lst)):
    min_ = min(copy)
    for k in copy:
        if k == min_:
            sort.append(min_)
    copy.remove(min_)
print(sort)

list.remove() removes the first occurrence of the value, not all such values. As a result you'll first add both 1 values to sort , remove one of the two 1 values, then add the remaining 1 value to sort again:

>>> lst = [4,5,5,1,6,1]
>>> copy = lst.copy()
>>> sort = []
>>> min_ = min(copy)
>>> min_
1
>>> for 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
>>> for k in copy:
...     if k == min_:
...         sort.append(min_)
... 
>>> sort
[1, 1, 1]

You could use a list comprehension to remove all values, by essentially creating a new copy that excludes the value to remove by filtering:

copy = [v for v in copy if v != min_]

This is not very efficient, of course.

Note that the next problem you'll run into is that you'll have emptied out copy before you have completed all range(len(lst)) iterations. You could replace that loop with a while copy: loop instead.

Alternatively, you could just add the first match of the min_ value to sort :

for i in range(len(lst)):
    min_ = min(copy)
    for k in copy:
        if k == min_:
            sort.append(min_)
            break
    copy.remove(min_)

The break ends the for loop early. Of course, you don't even have to loop to find that minimum value, that is what the min() call already did , so you can drop it altogether:

for i in range(len(lst)):
    min_ = min(copy)
    sort.append(min_)
    copy.remove(min_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM