• python去除重复元素


    目的:让我们两个列表压缩后,去除重复的点;

    1.set()方法:

    蓦然回首,那人却在灯火阑珊处;

    这个方法实现了我想要的压缩后的列表的重复删除;  

    list4 = [0,0,1,2,4,5,6,7,5,0,2]
    list5 = [2,5,4,8,5,6,6,6,6,2,8]
    
    list6 = zip(list4,list5)
    list7 = list(list6)
    print(list7)
    a = list(set(list7))
    print(a)
    #结果:
    [(0, 2), (0, 5), (1, 4), (2, 8), (4, 5), (5, 6), (6, 6), (7, 6), (5, 6), (0, 2), (2, 8)]
    [(6, 6), (4, 5), (2, 8), (5, 6), (7, 6), (1, 4), (0, 5), (0, 2)]

    到今天我才发现这种方法有个缺点是顺序是乱的 (时间:2020-04-1420:24:02),想要不乱的顺序:

    https://www.cnblogs.com/xiao-yu-/p/12693855.html

    2.np.unique()方法:

    import numpy as np
    
    list1 = [0,0,1,2,4,5,6,7,5]
    list2 = np.unique(list1)
    print(list2)
    
    list4 = [0,0,1,2,4,5,6,7,5,0,2]
    list5 = [2,5,4,8,5,6,6,6,6,2,8]
    
    list6 = zip(list4,list5)
    list7 = list(list6)
    
    print(np.unique(list7))
    #结果:
    [0 1 2 4 5 6 7]#这个结果是我们想要的
    [0 1 2 4 5 6 7 8] #这个不是我们要的结果,相当于没把list(zip())中的小括号当整体对待

    3.pd.Series()方法:

    import pandas as pd
    
    list1 = [0,0,1,2,4,5,6,7,5]
    
    list3 = pd.Series(list1)
    print(list3.unique())
    
    list4 = [0,0,1,2,4,5,6,7,5,0,2]
    list5 = [2,5,4,8,5,6,6,6,6,2,8]
    
    list6 = zip(list4,list5)
    list7 = list(list6)
    
    list8 = pd.Series(list7)
    print(list8.unique())
    
    
    #结果:
    [0 1 2 4 5 6 7] #这个是我们想要的
    [(0, 2) (0, 5) (1, 4) (2, 8) (4, 5) (5, 6) (6, 6) (7, 6)]#这个也算是我们要的,但是就是()之间没有","

    4.遍历去除重复元素:

    list1 = [0,0,1,2,4,5,6,7,5]
    
    list9 = []
    for i in list1:
        if not i in list9:
            list9.append(i)
    print(list9)

    #结果:
    [0, 1, 2, 4, 5, 6, 7] #是我们想要的,就是中间多了","

    5.列表推导式:

    list1 = [0,0,1,2,4,5,6,7,5]
    
    list10 = []
    [list10.append(i) for i in list1 if not i in list10]
    print(list10)
    #结果:
    [0, 1, 2, 4, 5, 6, 7] #比上面简单多了,哈哈。

    6.再试试可恶的list7(list(zip)之后的):

    list4 = [0,0,1,2,4,5,6,7,5,0,2]
    list5 = [2,5,4,8,5,6,6,6,6,2,8]
    
    list6 = zip(list4,list5)
    list7 = list(list6)
    
    list9 = []
    for i in list7:
        if not i in list9:
            list9.append(i)
    print(list9)
    
    list10 = []
    [list10.append(i) for i in list7 if not i in list10]
    print(list10)

    #结果
    [(0, 2), (0, 5), (1, 4), (2, 8), (4, 5), (5, 6), (6, 6), (7, 6)]
    [(0, 2), (0, 5), (1, 4), (2, 8), (4, 5), (5, 6), (6, 6), (7, 6)]
    #这样也行啊,但是我选择set(),一句话的事
    #但是谨记缺点:乱序

    参考地址:

    https://www.cnblogs.com/zhangshuyang/p/8087895.html

    https://jingyan.baidu.com/article/f3e34a12ebd701f5eb6535c6.html

  • 相关阅读:
    Docsify 如何在一个 MD 文件中嵌入另外一个文件
    集合与条件、循环语句
    字典(当索引不好用时)
    序列(列表、元组、字符串)
    变量、数据类型和运算符
    Python基础知识
    计算机基础知识
    Windows环境下Python2和Python3的安装
    操作系统基础
    计算机硬件基础知识
  • 原文地址:https://www.cnblogs.com/xiao-yu-/p/12589365.html
Copyright © 2020-2023  润新知