Home > database >  How to remove duplicate months and years from python list? [duplicate]
How to remove duplicate months and years from python list? [duplicate]

Time:10-07

How can we remove duplicate months and years from python list? Here's my code it's not working fine I can't think of any solution it's urgent I need solution will anybody help me ? Please <3

a = ['26/09/2021', '29/09/2021','26/07/2021', '29/07/2021','26/07/2021', '29/09/2021','26/07/2022', '29/09/2022']


def rdm(l):
    l = sorted(list(set(l)))
    for i in l:
        print("/".join(i.split('/')[1:3]))

rdm(a)

Output :

07/2021
07/2022
09/2021
07/2021
09/2021
09/2022

Required output:

07/2021
07/2022
09/2021
09/2022

CodePudding user response:

Try this:

def rdm(l):
    month_year_parts = [x[x.index('/')   1:] for x in a]
    # alternatively, on each element you can also choose one of:
    #   x.partition('/')[-1]
    #   x.split('/', 1)[-1]

    l = sorted(list(set(month_year_parts)))
    for i in l:
        print(i)

rdm(a)

CodePudding user response:

You can use the following to remove duplicates from a list and extract months and year.

a = ['26/09/2021', '29/09/2021','26/07/2021', '29/07/2021','26/07/2021', '29/09/2021','26/07/2022', '29/09/2022']


def rdm(l):
    temp = []
    l = sorted(list(set(l)))
    for i in l:
        temp.append("/".join(i.split('/')[1:3]))
    temp = list(dict.fromkeys(temp))
    print(temp)

rdm(a)

CodePudding user response:

a = ['26/09/2021', '29/09/2021','26/07/2021', '29/07/2021','26/07/2021', '29/09/2021','26/07/2022', '29/09/2022']


def rdm(l):
    l = sorted(list(set(l)))
    arr=[]
    for i in l:
        b= "/".join(i.split('/')[1:3])
        arr.append(b)
        
    output = []
    for x in arr:
        if x not in output:
            output.append(x)
            print(x)

rdm(a)

You create an array where you append all your output then check for distinct ones.

Output:

['07/2021', '07/2022', '09/2021', '09/2022']

  • Related