Home  >  Q&A  >  body text

python - How to remove duplicate elements?


For example, the first line above contains 3:19 and 3:6. How to write code so that the final file only takes the first one encountered? In this example, select 3:19

高洛峰高洛峰2670 days ago739

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-28 09:26:47

    Because I don’t know whether your string is a string or something, so I will implement it in the form of a string first

    l = '0:13 1:9 2:14 3:19 4:12 3:19'
    d = {}
    result = []
    for _ in l.split():
        key = _.split(':')[0]
        if key not in d:
            d[key] = _
            result.append(d[key])
    
    print(result)
    print(result)
    
    # 输出
    ['0:13', '1:9', '2:14', '3:19', '4:12']

    reply
    0
  • ringa_lee

    ringa_lee2017-06-28 09:26:47

    from itertools import groupby
    
    str = '0:13 1:9 2:14 3:19 4:12 3:6'
    lst = str.split()
    lst.sort()
    
    g_lst = [list(g)[0] for k, g in groupby(lst, key=lambda x: x.split(':')[0])]
    print g_lst
    
    #['0:13', '1:9', '2:14', '3:19', '4:12']
    

    reply
    0
  • Cancelreply