zoukankan      html  css  js  c++  java
  • python之数组元素去重

    list = [1,2,13,1,31,21,13,1,3,13,1,31,211,1] # 具有重复元素的数组
    list1= [] #创建一个新的数组来存储无重复元素的数组
    for element in list :
      if(element not in list1):
        list1.append(element)

    print list1

    元素出现次数  https://www.cnblogs.com/kaibindirver/p/9866450.html

    出重更好的方法 https://blog.csdn.net/weixin_44520259/article/details/89764254

    一、用set方法去重后与原列表长度比较
    lst=[1,3,5,3,4,4,2,9,6,7]
    set_lst=set(lst)
    #set会生成一个元素无序且不重复的可迭代对象,也就是我们常说的去重
    if len(set_lst)==len(lst):
    print('列表里的元素互不重复!')
    else:
    print('列表里有重复的元素!')
    二、用append的方式把原列表中的元素添加到一个新列表,确保新列表里不存在重复的元素,然后比较两个列表
    lst=[1,3,5,8,9,9,0,0,3,3]
    new_list=[]

    for i in lst:
    if i not in new_list:
    new_list.append(i)
    #这样能确保新的列表里包含原列表里所有种类的元素,且元素互不重复

    if len(new_list)==len(lst):
    print('原列表里的元素互不重复!')
    else:
    print('原列表里有重复的元素!')
    三、用fromkeys的方法创建一个字典,因为字典的键会自动去重,所以可以比较字典和原列表的长度,跟方法一很像
    lst=[1,3,5,8,9,9,0,0]
    dic={}.fromkeys(lst)
    #这种方法建立字典,会把列表里的元素当做字典的键,由于字典的键不能重复,所以会自动去重
    if len(dic)==len(lst):
    print('列表里的元素互不重复!')
    else:
    print('列表里有重复的元素!')

  • 相关阅读:
    poj 3617 Best Cow Line
    POJ 1852 Ants
    Pairs
    codility MinAbsSum
    Codeforces Beta Round #67 (Div. 2)C. Modified GCD
    timus 1018. Binary Apple Tree
    C
    HDU 1299Diophantus of Alexandria
    BZOJ2155(?) R集合 (卡特兰数)
    CSP模拟赛 number (二分+数位DP)
  • 原文地址:https://www.cnblogs.com/kaibindirver/p/12669412.html
Copyright © 2011-2022 走看看