写代码的时候,总是会发现自己的基础不牢固。
以下代码为去除相同数字:
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,而不是在原来的基础上进行的操作。