We are working on a function that returns a new list that removes duplicate elements from the list. The chords I made didn't work out well I actually don't know how to start.
def remove_duplicates():
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
for t in t2:
t.append(t.remove())
return t
In conclusion, under the assumption that you do not have to maintain the order of the list, you can write as follows
def removeDup(origin):
return list(set(origin))
To explain the code,
When you create a data structure that has no duplicate elements (usually referred to as "unique"), you usually use set
.
Like the definition of a set, set stores "unique" objects in an orderly manner.
After removing duplicates by making it usable (list, triple, etc.) a set, Type conversion from set to list again to create a list with deduplication
Example:
originalList = [1, 2, 3, 1, 2, 5, 6, 7, 8]
mySet = set(originalList)
changedList = list(mySet)
noOrder = list(set(originalList)-set([1,2,3]))
print "originalList:", originalList
print "mySet:", mySet
print "changedList:", changedList
print "noOrder:", noOrder
Result:
originalList: [1, 2, 3, 1, 2, 5, 6, 7, 8]
mySet: set([1, 2, 3, 5, 6, 7, 8])
changedList: [1, 2, 3, 5, 6, 7, 8]
noOrder: [8, 5, 6, 7]
However, as shown in the noOrder, the set does not guarantee the order of the original list If you want to keep the original order, you need to use a different method.
*This method can only be used with Python 2.7 and above.
from collections import OrderedDict
originalList = [1, 2, 3, 1, 2, 5, 6, 7, 8]
list(OrderedDict.fromkeys(originalList))
© 2024 OneMinuteCode. All rights reserved.