Comprehensions मध्ये Python: List, Dictionary, Set

List Comprehensions

  • List comprehensions list मध्ये s तयार करण्याचा एक संक्षिप्त आणि कार्यक्षम मार्ग आहे Python.
  • list ते तुम्हाला विद्यमान पुनरावृत्ती(उदा.,, टपल, स्ट्रिंग) मधील प्रत्येक आयटमवर एक अभिव्यक्ती लागू करून list आणि अटीवर आधारित आयटम फिल्टर करून नवीन निर्माण करण्याची परवानगी देतात .
  • आकलनाची वाक्यरचना list अशी आहे: [expression for item in iterable if condition]

उदाहरण:

# List comprehension to generate a list of squares of numbers from 0 to 9  
squares = [x**2 for x in range(10)]  
print(squares)   # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  
  
# List comprehension to filter even numbers from a list  
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
even_numbers = [x for x in numbers if x % 2 == 0]  
print(even_numbers)   # Output: [2, 4, 6, 8, 10]  

 

Dictionary Comprehensions

  • Dictionary comprehensions तुम्हाला संक्षिप्त पद्धतीने शब्दकोश तयार करण्याची अनुमती देते.
  • प्रमाणेच, ते प्रत्येक आयटमला पुनरावृत्ती करण्यायोग्य आणि अटीवर आधारित फिल्टरिंग आयटममध्ये एक अभिव्यक्ती लागू करून list comprehensions नवीन व्युत्पन्न करतात. dictionary
  • आकलनाची वाक्यरचना dictionary अशी आहे: {key_expression: value_expression for item in iterable if condition}

उदाहरण:

# Dictionary comprehension to create a dictionary of squares of numbers from 0 to 9  
squares_dict = {x: x**2 for x in range(10)}  
print(squares_dict)   # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}  
  
# Dictionary comprehension to filter even numbers from a dictionary  
numbers_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}  
even_numbers_dict = {key: value for key, value in numbers_dict.items() if key % 2 == 0}  
print(even_numbers_dict)   # Output: {2: 'two', 4: 'four'}  

 

Set Comprehensions

  • Set comprehensions तुम्हाला आणि set सारख्याच प्रकारे s तयार करण्याची अनुमती देते. list comprehensions dictionary comprehensions
  • set ते पुनरावृत्ती करण्यायोग्य आणि स्थितीवर आधारित आयटम फिल्टर करून प्रत्येक आयटमवर एक अभिव्यक्ती लागू करून एक नवीन व्युत्पन्न करतात .
  • आकलनाची वाक्यरचना set अशी आहे: {expression for item in iterable if condition}

उदाहरण:

# Set comprehension to create a set of squares of numbers from 0 to 9  
squares_set = {x**2 for x in range(10)}  
print(squares_set)   # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}  
  
# Set comprehension to filter even numbers from a set
numbers_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}  
even_numbers_set = {x for x in numbers_set if x % 2 == 0}  
print(even_numbers_set)   # Output: {2, 4, 6, 8, 10}

 

Comprehensions तुमचा कोड अधिक शोभिवंत आणि कार्यक्षम बनवून, विद्यमान पुनरावृत्तीच्या आधारे s, शब्दकोश आणि s Python तयार करण्यासाठी एक संक्षिप्त आणि वाचनीय मार्ग प्रदान करा. list set