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


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

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

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的解釋


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM