Python collections Module
In this page:
from collections import Counter, defaultdict, deque, namedtuple
counter = Counter(iterable)
groups = defaultdict(list)
queue = deque(iterable)
Counter से Items गिनना
Counter एक dict subclass है जो खासतौर पर गिनने के लिए बना है: उसे कोई भी iterable देना अपने आप गिन लेता है कि हर element कितनी बार आता है, एक manual loop-and-increment pattern को एक ही constructor call में बदल देता है।
यह counters के बीच arithmetic और ranked frequency results के लिए most_common() method भी support करता है।
उदाहरण: Counting Items with Counter
from collections import Counter
counts = Counter(["a", "b", "a", "c", "a"]) # tallies how many times each item appears
print(counts)
print(counts.most_common(1)) # the single most frequent item
defaultdict से Grouping
defaultdict एक dict subclass है जो missing key access होने पर KeyError raise करने की बजाय (आपके दिए गए factory, जैसे list या int, के ज़रिए) अपने आप एक default value दे देता है।
यह per-key list में append करने या per-key counter बढ़ाने से पहले if key not in dict जाँचने की ज़रूरत हटा देता है।
उदाहरण: Grouping with defaultdict
from collections import defaultdict
groups = defaultdict(list) # missing keys default to a new empty list
groups["fruits"].append("apple") # no need to check if "fruits" exists first
print(groups)
namedtuple से Named Tuples
namedtuple एक lightweight, immutable tuple subclass generate करता है जिसके fields के positions के साथ-साथ names भी होते हैं, ताकि आप कम readable point[0] की बजाय point.x लिख सकें।
यह plain tuple (कोई names नहीं) और पूरी class (एक साधारण record के लिए ज़्यादा machinery) के बीच एक अच्छा middle ground है।
उदाहरण: Named Tuples with namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"]) # tuple subclass with named fields
p = Point(1, 2)
print(p.x, p.y) # access by name instead of index
deque से Double-Ended Queue
deque दोनों सिरों से O(1) appends और pops support करता है, plain list के विपरीत, जहाँ शुरुआत से हटाना O(n) है क्योंकि बाकी हर element को shift होना पड़ता है।
यह deque को queue, sliding window, या नियमित रूप से दोनों तरफ़ से जोड़ने-हटाने वाली किसी भी चीज़ के लिए सही structure बनाता है।
उदाहरण: Double-Ended Queue with deque
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0) # O(1) insert at the front
d.append(4) # O(1) insert at the back
print(d)
OrderedDict से Dictionary Ordering
OrderedDict explicitly key insertion order बनाए रखता है और entries को मांग पर reorder करने के लिए move_to_end() जैसे extras जोड़ता है।
Python 3.7 से plain dicts भी language गारंटी के तौर पर insertion order बनाए रखते हैं, इसलिए अब OrderedDict मुख्यतः खुद ordering की बजाय उस extra reordering functionality के लिए उपयोगी है।
उदाहरण: Dictionary Ordering with OrderedDict
from collections import OrderedDict
d = OrderedDict()
d["a"] = 1
d["b"] = 2
d.move_to_end("a") # moves "a" to the end without removing it
print(d)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: