my_list = [1,2,3,4,2,3]
so my desired list should be like
new_list = [1,4]
duplicate values should be removed along with the original ones
Attempt -
output = []
for x in my_list:
if x not in output:
output.append(x)
print(output)
CodePudding user response:
One option is to use collections.Counter
, and then filter out items of multiple appearances:
[v for v, c in collections.Counter([1, 2, 3, 4, 2, 3]).items() if c == 1]
The Counter
will create a dictionary with the items: Counter({1: 1, 2: 2, 3: 2, 4: 1})
.
CodePudding user response:
You can use collections.Counter
like below:
>>> from collections import Counter
>>> my_list = [1,2,3,4,2,3]
>>> dct_cnt = Counter(my_list)
>>> [k for k,v in dct_cnt.items() if v ==1]
[1, 4]
CodePudding user response:
You can use the .count()
method of the lists, along with a list comprehension.
For example:
my_list = [1,2,3,4,2,3]
new_list = [x for x in my_list if l.count(x) == 1]
print(new_list) # Prints [1,4]
CodePudding user response:
all approaches are good I want to add a different approach
def duplicate_deleter(list_object):
set_obj=set(list_object)
result=[]
for i in set_obj:
if list_object.count(i)==1:
result.append(i)
return result
CodePudding user response:
Without collections you can use a dictionary to count the frequency of the items in the list then keep only those with low enough frequency. This example runs in O(n m) where n is the number of elements in the original list and m is the number of unique elements.
lst = [1,2,2,3,4,5,4]
freq = dict()
for el in lst:
if el in freq:
freq[el] = 1
else:
freq[el] = 1
print([el for el, f in freq.items() if f < 2])
CodePudding user response:
You can create a program to pop the list x number of times for each duplicate element, where x is equals to the count of a duplicate element in the list.
my_list = [1,2,3,4,2,3]
#Sort the list so the index matches the count arrays index
my_list.sort()
#Create the count array using set to count each unique element
count = [my_list.count(x) for x in set(my_list)]
#Create another count to cycle through the count array
count1 = 0
#Create a popped variable to keep record of how many times the list has been altered
popped = 0
while (count1 < len(count)):
if count[count1] > 1:
#Create a variable to pop r number of times depending on the count
r = 0
while (r < count[count1]):
#If the list has already been popped, the index to be examined has to be the previous one.
#For example, after the 2's have been popped we want it to check the first 3
#which is now in the count1-1 index.
my_list.pop((count1 - popped))
r = r 1
popped = popped 1
count1 = 1
print(my_list)
else:
count1 = 1