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()
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值