python列表排序不改变顺序

去重可以乱序
lis = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
lis2 = list(set(lis))
print(lis2)
去重不改变原始顺序

本质上 func1、func3 和 func6原理是一样的,将列表遍历一次,第一次出现到放到新到列表中
func2、func4 和 func5原理是一样的,先将列表去重,然后按原始列表的索引重新排序

from functools import reduce


def func1():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    list_non_duplicate = []
    for i in list_duplicate:
        if i not in list_non_duplicate:
            list_non_duplicate.append(i)
    print(list_non_duplicate)


def func2():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    list_non_duplicate = list(set(list_duplicate))
    list_non_duplicate.sort(key=list_duplicate.index)
    print(list_non_duplicate)


def func3():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    list_non_duplicate = []
    for i, v in enumerate(list_duplicate):
        if list_duplicate.index(v) == i:  # todo 值v是第一次出现,添加到新列表中
            list_non_duplicate.append(v)
    print(list_non_duplicate)


def func4():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    list_non_duplicate = list_duplicate[:]
    for i in list_duplicate:
        while list_non_duplicate.count(i) > 1:  # todo  list_non_duplicate 去重
            del list_non_duplicate[list_non_duplicate.index(i)]
    list_non_duplicate.sort(key=list_duplicate.index)
    print(list_non_duplicate)


def func5():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    list_non_duplicate = sorted(set(list_duplicate), key=list_duplicate.index)
    print(list_non_duplicate)


def func6():
    list_duplicate = [3, 1, 4, 3, 6, 3, 2, 4, 9, 1]
    func = lambda list_n_d, i: list_n_d if i in list_n_d else list_n_d + [i]
    list_non_duplicate = reduce(func, [[]] + list_duplicate)
    print(list_non_duplicate)


if __name__ == '__main__':
    func1()
    func2()
    func3()
    func4()
    func5()
    func6()

你可能感兴趣的:(python基础,python,列表)