繁体   English   中英

删除列表中的重复项并检查它是否与另一个列表相同

[英]Remove duplicates in a list and check whether it's the same as another list

我的任务是实现'remove_extra(lst)',这样它就会获取一个列表并返回相同的列表,并删除所有重复的出现。 注意:返回列表中元素的顺序无关紧要。 提示:您可以使用sort或任何其他python列表函数来使您的生活更轻松。

我得到了:

lst1 = [1, 5, 1, 1, 3]
lst2 = [2, 2, 2, 1, 5, 4, 4]
result1 = remove_extra(lst1)
result2 = remove_extra(lst2)

执行以下表达式时:

(result1 is lst1)
(result2 is lst2)

我应该为两个表达式都得到True但我的输出是False。 请帮我查一下我的代码:

def remove_extra(lst):
    new_lst = []
    for i in lst:
        if i not in new_lst:
        new_lst.append(i)

    return new_lst

如果需要就地更改lst ,请指定整个切片; 使用set()生成一系列唯一值而不是循环:

def remove_extra(lst):
    lst[:] = set(lst)
    return lst

分配给切片会替换列表中的元素 ,而不是重新绑定名称lst 对于标识切片(从第一个元素到最后一个元素),这意味着我们用赋值右侧的序列中包含的任何元素替换所有元素。 lst[:] = set(lst)替换所有元素lst与该中的同一列表的元素。

但是,最好不要为就地操作返回相同的列表对象。 没有什么意义,原来的名单已经改变了; 当可变对象被直接更改时,Python内置类型总是返回None

演示:

>>> lst1 = [1, 5, 1, 1, 3]
>>> def remove_extra(lst):
...     lst[:] = set(lst)
...     return lst
... 
>>> lst1 = [1, 5, 1, 1, 3]
>>> result1 = remove_extra(lst1)
>>> result1 is lst1
True
>>> lst1
[1, 3, 5]
>>> lst2 = [2, 2, 2, 1, 5, 4, 4]
>>> result2 = remove_extra(lst2)
>>> result2 is lst2
True

我通常会使用list(set(...))实现,但只是为了好玩,这里有一个不同的方式:

L = [2, 2, 2, 1, 5, 4, 4]
L.sort()
i = 0
while i<len(L)-1:
    print("j:", j)
    while L[i]==L[j] and j<len(L):
        L.pop(j)
    i += 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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