Home > database >  remove duplicates and keep the rightmost value and unique numbers in list
remove duplicates and keep the rightmost value and unique numbers in list

Time:01-30

I want to remove the duplicates but keep the last occurrence of it. Also want to keep the unique value. but these all must follow in the order of the list.

Example 1: list = [3, 4, 4, 5, 4, 4 ,7, 7] OUPTUT: 3,5,4,7

Example 2: list = [3, 3, 5, 3, 5] OUTPUT: 3,5

CodePudding user response:

Here's an elegant one-liner :

answer = lambda l: list(dict.fromkeys(l[::-1]))[::-1]

print(answer([3, 4, 4, 5, 4, 4 ,7, 7])) # [3, 5, 4, 7]
print(answer([3, 3, 5, 3, 5])) # [3, 5]

But use this instead (best practice to not name anonymous functions) :

def answer(l):
    return list(dict.fromkeys(l[::-1]))[::-1]

print(answer([3, 4, 4, 5, 4, 4 ,7, 7])) # [3, 5, 4, 7]
print(answer([3, 3, 5, 3, 5])) # [3, 5]

(both answers work with other inputs as well)

CodePudding user response:

l=[int(x) for x in input("Enter the list of numbers:").split()]
dupl=[]
for i in l:
    if i not in dupl:
        dupl.append(i)
    else:
        del dupl[dupl.index(i)]
        dupl.append(i)
print(dupl)

CodePudding user response:

Simply make a counter of all the elements and remove the first element if the counter is still more than 1.

Use the copy of the list using list[:]

import collections
list = [3, 4, 4, 5, 4, 4 ,7, 7]
frequency = dict(collections.Counter(list)) #{3:1,4:4, 5:2, 7:2}
for item in list[:]:
  if frequency[item] > 1:
    frequency[item] -= 1
    list.remove(item)

print(list)

or

Create a new list

import collections
list = [3, 4, 4, 5, 4, 4 ,7, 7]
result = []
frequency = dict(collections.Counter(list)) #{3:1,4:4, 5:2, 7:2}
for item in list:
  if frequency[item] > 1:
    frequency[item] -= 1
  else:
    result.append(item)
print(result)

CodePudding user response:

Maybe I've missed something in the question, but you can achieve this directly using set in python. For example:

ls = [3, 4, 4, 5, 4, 4 ,7, 7]
set_ls = set(ls)
print(set_ls)

And you'll be able to remove all the duplicates, also to convert it to a list again, just do a list(set_ls)

CodePudding user response:

Python has a built-in method for dictionaries that is dict.fromkeys()
you can fix your problem with:

mylist = [3, 3, 5, 3, 5]
mylist = list(dict.fromkeys(mylist))
print(mylist)

and Output is: [3, 5]

  •  Tags:  
  • Related