【问题标题】:changing the original list inside function更改函数内部的原始列表
【发布时间】:2019-04-24 21:34:14
【问题描述】:

需要创建一个在不更改原始列表的情况下删除重复项的函数。 而在第二个中,它需要更改原始列表并且什么也不返回。 这里的问题是第二个函数只适用于一个重复而不适用于 2 个不同的数字(它只是删除一个数字(它不适用于 [2,3,4,5,3,4] 但适用于 [1,2, 3,3]

def drop_duplicates(lst):
    s = []
    # Write the rest of the code for question 3a below here.
    for i in lst:
       if i not in s:
           s.append(i)
    return s
lst = [1, 2, 3, 2, 4, 2]
print drop_duplicates(lst)
print lst

def drop_duplicates_in_place(lst):
    # Write the rest of the code for question 3b below here.
    for i in range(len(lst) - 1):
        for j in range ( i+1, len(lst) - 1):
            if lst[i] == lst[j]:
                lst.pop(j)
            else:
                continue

lst = [1, 2, 3, 2, 4, 2] 
print lst

【问题讨论】:

    标签: python python-2.7 duplicates


    【解决方案1】:

    内循环范围太短:

    for i in range(len(lst) - 1):
        for j in range(i+1, len(lst)):  # no -1 here
    

    此外,您实际上并不需要循环体中的 else 部分。通常,嵌套循环和从列表的(中间)重复删除在性能方面并不理想。在保持线性出现顺序的同时删除重复项的推荐方法是使用collections.OrderedDict。要使其就地,您可以使用切片分配:

    from collections import OrderedDict
    
    def drop_duplicates_in_place(lst):
        lst[:] = OrderedDict.fromkeys(lst)
    

    【讨论】:

    • @sereenmasalha 出于利益考虑,这在 python 3.6+ 中有效,无需导入,因为默认情况下对字典进行排序。 lst[:] = dict.fromkeys(lst)
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2012-12-18
    相关资源
    最近更新 更多