Python map() और filter()
In this page:
map(function, iterable)
filter(function, iterable)
list(map(lambda x: expression, iterable))
map() Function
map(function, iterable) दिए गए function को iterable के हर element पर लागू करता है और results का एक lazy iterator return करता है, list नहीं -- अगर आपको actual values चाहिए, न कि सिर्फ एक iterator जिस पर एक बार loop चला सकें, तो इसे list() में wrap करें।
उदाहरण: The map() Function
nums = [1, 2, 3]
result = map(str, nums) # returns a lazy iterator, not a list
print(list(result)) # materialize it to see the values
map() और Lambda के साथ
map() को lambda के साथ जोड़ने से आप बिना पहले कोई अलग named function define किए, inline ही एक quick, disposable transformation apply कर सकते हैं, जो list के हर number को square करने जैसे सरल one-line operations के लिए सुविधाजनक है।
उदाहरण: map() with Lambda
nums = [1, 2, 3]
squares = map(lambda x: x * x, nums) # inline transformation, no separate named function
print(list(squares))
filter() Function
filter(function, iterable) सिर्फ उन elements को रखता है जिनके लिए दिया गया function एक truthy value return करता है, बाकी को discard कर देता है -- map() की तरह, यह भी list नहीं बल्कि एक lazy iterator return करता है, इसलिए concrete results चाहिए तो इसे भी list() में wrap करना होता है।
उदाहरण: The filter() Function
def is_even(n):
return n % 2 == 0
nums = [1, 2, 3, 4, 5, 6]
print(list(filter(is_even, nums))) # keeps only elements where is_even returns True
filter() और Lambda के साथ
filter() के अंदर एक lambda quick, inline conditions देने का आम pattern है, जैसे सिर्फ even numbers रखने के लिए filter(lambda x: x % 2 == 0, numbers), बिना सिर्फ इसी एक इस्तेमाल के लिए अलग से is_even function define किए।
उदाहरण: filter() with Lambda
nums = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, nums) # inline condition instead of a named function
print(list(evens))
map() और filter() को मिलाना
filter() के इर्द-गिर्द map() को nest करना आपको एक sequence को उन elements तक filter करने देता है जिनकी आपको परवाह है और फिर सिर्फ उन बचे हुए elements को एक ही expression में transform करने देता है -- हालाँकि सरल मामलों से आगे, map() और filter() को एक साथ stack करने की बजाय आमतौर पर list comprehension ज़्यादा साफ पढ़ी जाती है।
उदाहरण: Combining map() and filter()
nums = [1, 2, 3, 4, 5, 6]
result = map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums)) # filter first, then transform the survivors
print(list(result))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects