If I have a list say l = [1, 8, 8, 8, 1, 3, 3, 8]
and it's guaranteed that every element occurs an even number of times, how do I make a list with all elements of l
now occurring n/2
times. So since 1
occurred 2
times, it should now occur once. Since 8
occurs 4
times, it should now occur twice. Since 3
occurred twice, it should occur once.
So the new list will be something like k=[1,8,8,3]
What is the fastest way to do this? I did list.count()
for every element but it was very slow.
The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given. The combination of list comprehension and enumerate is used to remove the duplicate elements from the list.
Using set() A simple and fast approach to remove duplicate elements from list in Python would be to use Python's built-in set() method to convert the list elements into a unique set, following which we can convert it into a List now removed of all its duplicate elements.
Remove duplicates from list operation has large number of applications and hence, it’s knowledge is good to have. In naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element.
In other of elements is maintained in the output array using the 'key'. Consider the key is of length O (n), the time taken for performing sorting on the key and value is O (nlogn). So the time taken to delete all duplicates from the array is O (nlogn).
Hence, if we cast a list to a set, duplicates will be removed. However, the original order of elements is not guaranteed. The order of elements in a set is decided by hashing mechanism, which may be different than in the list.
I mean that for the set of source objects S, given any two objects x1 and x2 that are elements of S there exists a (hash) function F such that: Java has such a relationship. That allows you to check to duplicates as a near O (1) operation and thus reduces the algorithm to a simple O (n) problem. If order is unimportant, it's a simple one liner:
If order isn't important, a way would be to get the odd or even indexes only after a sort. Those lists will be the same so you only need one of them.
l = [1,8,8,8,1,3,3,8] l.sort() # Get all odd indexes odd = l[1::2] # Get all even indexes even = l[::2] print(odd) print(odd == even)
Result:
[1, 3, 8, 8] True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With