اذهب إلى المحتوى
  • 0

إزالة الحروف المكررة من القائمة في لغة بايثون

فرح احمد

السؤال

Recommended Posts

  • 0

هناك عدة طرق ولكن أشهر هذه الطرق التالي

  • استخدام set حيث سيتم إنشاء set وأثناء إنشاء ال set يتم مسح العناصر المكررة كالتالي
    mylist = ["a", "b", "a", "c", "c"]
    mylist = list( set(mylist) )

     

  • أو استخدام ال dict.fromkeys وهذه الطريقة تقوم بإنشاء directory وأثناء إنشائه يتم مسح العناصر المكررة تلقائياً كالتالي
    mylist = ["a", "b", "a", "c", "c"]
    mylist = list( dict.fromkeys(mylist) )

     

الفرق أن الطريقة الأولى لا تحافظ على ترتيب العناصر ولكن الطريقة الثانية تحافظ علي الترتيب

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

لدينا العديد من طرق 

  • باستخدام loop و بدون استخدام اي method 
    test_list = [1, 3, 5, 6, 3, 5, 6, 1]
    print ("The original list is : " +  str(test_list))
    res = []
    for i in test_list:
        if i not in res: # list غير موجود داخل  item لو 
            res.append(i)
    # printing list after removal 
    print ("The list after removing duplicates : " + str(res))
    
    
    Output :
    
    The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
    The list after removing duplicates : [1, 3, 5, 6]

    هذه طريقة سهله و يمكن تنفيذ بدون معرفة مسبقة 

  • باستخدام set 
    الفرق اﻷساسي بين list و set هو أن set لا تقبل أشياء مكرره 
     

    # initializing list
    test_list = [1, 5, 3, 6, 3, 5, 6, 1]
    print ("The original list is : " +  str(test_list))
    
    # using set()
    # to remove duplicated 
    # from list 
    test_list = list(set(test_list))
    
    print ("The list after removing duplicates : " + str(test_list))
    
    Output :
    
    The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
    The list after removing duplicates : [1, 3, 5, 6]

     

  • مع python 3 جاءت بما يسمي list comprehension

    test_list = [1, 3, 5, 6, 3, 5, 6, 1]
    print ("The original list is : " +  str(test_list))
      
    # using list comprehension
    res = []
    [res.append(x) for x in test_list if x not in res]
      
    # printing list after removal 
    print ("The list after removing duplicates : " + str(res))
    
    Output :
    
    
    
    The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
    The list after removing duplicates : [1, 3, 5, 6]

    أذا قمت بالملاحظه ستجد أنه نفس طريقة الاول لكن بكود أفضل و أقل

  • يمكنن أيضا استخدام Using collections.OrderedDict.fromkeys 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...