对数组 [3, 1, 2, 4, 2, 4, 5, 3, 7] 进行去重, 写出至少两种方法 (请写出一段Python代码实现删除一个list里面的重复元素)

1. 对数组 [3, 1, 2, 4, 2, 4, 5, 3, 7] 进行去重, 写出至少两种方法 (请写出一段Python代码实现删除一个list里面的重复元素)

In [1]:
def unique1(lst):
    '''内置方法'''
    return list(set(lst))
def unique2(lst):
    '''思路简单'''
    l = []
    for i in lst:
        if i not in l:
            l.append(i)
    return l
def unique3(lst):
    for i in lst.copy():
        if lst.count(i) > 1:
            lst.remove(i)
    return lst
def unique4(lst):
    '''位图去重, 仅限于正整数'''
    bmp = 0
    l = []
    for i in lst:
        n = (1 << i)
        if bmp & n == 0:
            bmp |= n
            l.append(i)
    return l
l = [3, 1, 2, 4, 2, 4, 2, 5, 3, 7]
print(unique1(l.copy()))
print(unique2(l.copy()))
print(unique3(l.copy()))
print(unique4(l.copy()))

[1, 2, 3, 4, 5, 7]
[3, 1, 2, 4, 5, 7]
[1, 4, 2, 5, 3, 7]
[3, 1, 2, 4, 5, 7]

猜你喜欢

转载自blog.csdn.net/cats_miao/article/details/80843520