-2

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.

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
James Z
  • 12,209
  • 10
  • 24
  • 44

3 Answers3

1

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)
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
0

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)

ewertonvsilva
  • 1,795
  • 1
  • 5
  • 15
0
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']