1. 程式人生 > >Python列表list應用於去除相同數字

Python列表list應用於去除相同數字

自己的 append 自帶 存在 strong .py through python 初始

寫代碼的時候,總是會發現自己的基礎不牢固。

以下代碼為去除相同數字:

def remove_duplicates(inputlist):
    if inputlist == []:
        return []
    
    # Sort the input list from low to high    
    inputlist = sorted(inputlist)
    # Initialize the output list, and give it the first value of the now-sorted input list
    outputlist = [inputlist[0]]

    
# Go through the values of the sorted list and append to the output list # ...any values that are greater than the last value of the output list for i in inputlist: if i > outputlist[-1]: outputlist.append(i) return outputlist print remove_duplicates([1, 1, 2, 2])

這裏outputlist[-1]是outputlist這個隊列裏倒數第一個元素。

先把inputlist排序,排序的算法是程序自帶的sorted函數。然後初始化outputlist,把inputlist中的第一個元素加進去。然後對inputlist裏的元素進行操作。

sort 與 sorted 區別:

sort 是應用在 list 上的方法,sorted 可以對所有可叠代的對象進行排序操作。

list 的 sort 方法返回的是對已經存在的列表進行操作,無返回值,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。

Python文檔sorted的解釋

Python列表list應用於去除相同數字