Hoe om duplikate van 'n Python-lys te verwyder
Leer hoe om duplikate van 'n lys in Python te verwyder.
Voorbeeld
Verwyder enige duplikate van 'n lys:
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Voorbeeld Verduidelik
Eerstens het ons 'n lys wat duplikate bevat:
'n Lys met duplikate
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Skep 'n woordeboek deur die Lys-items as sleutels te gebruik. Dit sal outomaties enige duplikate verwyder omdat woordeboeke nie duplikaatsleutels kan hê nie.
Skep 'n woordeboek
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Skakel dan die woordeboek terug in 'n lys:
Skakel om in 'n lys
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Nou het ons 'n Lys sonder enige duplikate, en dit het dieselfde volgorde as die oorspronklike Lys.
Druk die lys om die resultaat te demonstreer
Druk die lys
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Skep 'n funksie
As jy graag 'n funksie wil hê waarheen jy jou lyste kan stuur, en dit sonder duplikate kan terugkry, kan jy 'n funksie skep en die kode van die voorbeeld hierbo invoeg.
Voorbeeld
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
Voorbeeld Verduidelik
Skep 'n funksie wat 'n Lys as 'n argument neem.
Skep 'n funksie
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
Skep 'n woordeboek deur hierdie lysitems as sleutels te gebruik.
Skep 'n woordeboek
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
Skakel die woordeboek om in 'n lys.
Skakel om in 'n lys
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
Gee die lys terug
Terugkeer lys
def my_function(x):
return list(dict.fromkeys(x))
mylist =
my_function(["a", "b", "a", "c", "c"])
print(mylist)
Roep die funksie op, met 'n lys as 'n parameter:
Roep die funksie
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)
Druk die resultaat:
Druk die resultaat
def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)