كيفية إزالة العناصر المكررة من قائمة بايثون
تعلم كيفية إزالة العناصر المكررة من القائمة في بايثون.
实例
إزالة أي عنصر مكرر من القائمة:
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
توضيح المثال
أولاً، لدينا قائمة تحتوي على تكرارات:
القائمة تحتوي على تكرارات
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
استخدام عنصر القائمة ك مفتاح لإنشاء دليل. سيتم حذف أي عنصر مكرر تلقائيًا، لأن الدليل لا يمكن أن يحتوي على مفاتيح مكررة.
创建字典
mylist = ["a", "b", "a", "c", "c"] mylist = list( dict.fromkeys(mylist) ) print(mylist)
ثم، قم بتحويل الدليل إلى قائمة:
تحويل إلى قائمة
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
الآن لدينا قائمة لا تحتوي على تكرارات، وتتطابق مع ترتيب القائمة الأصلية.
打印列表以演示结果:
打印 List
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
创建函数
如果您希望有一个函数可以发送列表,然后它们返回的无重复项,则可以创建函数并插入上例中的代码。
实例
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
例子解释
创建一个以 List 作为参数的函数。
创建函数
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
使用此 List 项作为键创建字典。
创建字典
def my_function(x): return list( dict.fromkeys(x) ) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
将字典转换为列表:
转换为列表
def my_function(x): return list( dict.fromkeys(x) ) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
返回列表:
返回列表
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
使用列表作为参数来调用该函数:
调用函数
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)
打印结果:
打印结果
def my_function(x): return list(dict.fromkeys(x)) mylist = my_function(["a", "b", "a", "c", "c"]) print(mylist)