اشتقاق القواميس والمجموعات
تماماً مثل القوائم، يمكن إنشاء القواميس والمجموعات باستخدام صيغة اشتقاق مدمجة في سطر واحد.
اشتقاق المجموعات (Set Comprehension)
الصيغة: {expression for item in iterable}
python
الهدف: الحصول على أطوال الكلمات الفريدة
words = ['hello', 'world', 'python', 'hello']
lengths_set = {len(w) for w in words} print(lengths_set) # المخرجات: {5, 6}
مثال 2: تربيع الأرقام الفريدة من قائمة
numbers = [1, 2, 2, 3, 4, 3, 1] unique_squares = {n ** 2 for n in numbers} print(unique_squares) # المخرجات: {1, 4, 9, 16}
اشتقاق القواميس (Dictionary Comprehension)
الصيغة: {key_expression: value_expression for item in iterable}
python
الهدف: إنشاء قاموس يربط الأحرف بنسختها الكبيرة
letters = ['a', 'b', 'c']
mapping = {k: k.upper() for k in letters} print(mapping) # {'a': 'A', 'b': 'B', 'c': 'C'}
مثال 2: التصفية المشروطة في القواميس
stock_prices = {'AAPL': 150, 'GOOG': 2800, 'TSLA': 600, 'AMZN': 3000}
تضمين الأسهم التي يقل سعرها عن 1000 فقط
low_stocks = {ticker: price for ticker, price in stock_prices.items() if price < 1000} print(low_stocks) # {'AAPL': 150, 'TSLA': 600}