לדלג לתוכן

2.3 קומפרהנשין הרצאה

ליסט קומפרהנשין - List comprehension

  • ליסט קומפרהנשין הוא תחביר מיוחד בפייתון המאפשר ליצור רשימות בצורה תמציתית וקריאה יותר. בעזרת list comprehension ניתן לכתוב ביטויים לוגיים ופעולות על כל אחד מהאלמנטים ברשימה בצורה קצרה ויעילה.

  • איך בדרך כלל אנחנו יוצרים רשימות:

    l = []
    for x in range(1, 10):
        l.append(x)
    

  • בעזרת ליסט קומפרהנשין אנחנו נכתוב את כל מה שנכתב בקוד למעלה בשורה אחת. ראו דוגמה:

    l = [x for x in range(1, 10)]
    

  • אם נרצה ליצור רשימה עם שימוש בתנאים:

    l = []
    for x in range(1, 10):
        if x != 5:
            l.append(x)
    

  • אותו הקוד, רק בעזרת ליסט קומפרהנשין:

    l = [x for x in range(1, 10) if x != 5]
    

  • שימוש ב if ו - else:

    l = []
    for x in range(1, 10):
        if x != 5:
            l.append(x)
        else:
            l.append(999)
    

  • אותו הקוד, רק בעזרת ליסט קומפרהנשין:

    l = [x if x != 5 else 999 for x in range(1, 10)]
    

דיקשנרי קומפרהנשין - Dictionary comprehension

  • דיקשנרי קומפרהנשין הוא תחביר בפייתון המאפשר ליצור מילונים בצורה תמציתית וקריאה יותר, בדיוק כמו List Comprehension עבור רשימות.

  • איך בדרך כלל אנחנו יוצרים מילון:

    d = {}
    for num in range(1, 10):
        d[num] = num * num
    

  • דיקשנרי קומפרהנשין

    d = {num: num*num for num in range(1, 10)}
    

  • דוגמה מורכבת:

    old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
    dollar_to_pound = 0.76
    new_price = {}
    
    for (item, value) in old_price.items():
        new_price[item] = value * dollar_to_pound
    

  • דיקשנרי קומפרהנשין

    new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()}
    

זיפ - zip

  • הפונקציה zip בפייתון משמשת לשילוב של מספר איטרטורים (כמו רשימות או טאפלים) לאיטרטור אחד של טאפלים. כל טאפלה מכיל את הפריטים המתאימים מאותו אינדקס מכל האיטרטורים.

  • דוגמה 1: איחוד שני רשימות:

    names = ['Alice', 'Bob', 'Charlie']
    ages = [25, 30, 22]
    
    # Combine names and ages using zip
    combined_data = zip(names, ages)
    
    # Convert the result to a list of tuples
    result = list(combined_data)
    print(result) # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 22)]
    
    # Convert the result to a dictionary
    result = dict(result)
    print(result) # Output: {'Alice': 25, 'Bob': 30, 'Charlie': 22 }
    

  • דוגמה 2: לעבור על מספר דברים בו זמנית בלולאת for

    fruits = ['Apple', 'Banana', 'Orange']
    colors = ['Red', 'Yellow', 'Orange']
    
    # Iterate over both lists simultaneously using zip
    for fruit, color in zip(fruits, colors):
        print(f"The {fruit} is {color}")