Python's collections-Modul erkunden

PythonPythonBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Einführung

In diesem Tutorial werden wir das integrierte Python-Modul collections erkunden. Das Modul collections ist eine leistungsstarke Bibliothek, die eine Vielzahl von Container-Datentypen bietet, die die Funktionalität der in Python eingebauten Container wie Listen, Tupel und Wörterbücher erweitern.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/lists -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/tuples -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/dictionaries -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/function_definition -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/default_arguments -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/importing_modules -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/standard_libraries -.-> lab-7837{{"Python's collections-Modul erkunden"}} python/data_collections -.-> lab-7837{{"Python's collections-Modul erkunden"}} end

NamedTuple

Ein namedtuple ist eine Unterklasse von Tupeln, die benannte Felder bietet, um den Code lesbarer und selbsterklärend zu machen. Erstellen wir in named_tuple.py ein namedtuple, um einen Punkt im 2D-Raum darzustellen:

## Import collections
from collections import namedtuple

## Definiere einen namedtuple-Typ Point mit x- und y-Eigenschaften
Point = namedtuple('Point', ['x', 'y'])

## Erstelle ein Poinit-Objekt
p = Point(1, 2)

## Rufe die Eigenschaften des Punktes ab
print(p.x)
print(p.y)

Führen Sie dann das Skript im Terminal aus:

python named_tuple.py

Ausgabe:

1
2

Counter

Counter ist eine Unterklasse von dict, die die Vorkommen von Elementen in einer Sammlung zählt. Erstellen wir in counter.py ein Counter-Objekt, um die Vorkommen von Zeichen in einem String zu zählen:

from collections import Counter

text = "hello, world!"
## Holt die Anzahl der Vorkommen der Elemente in der Sammlung und gibt sie als Dictionary zurück
char_count = Counter(text)

print(char_count)

Führen Sie dann das Skript im Terminal aus:

python counter.py

Ausgabe:

Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1,'': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})

OrderedDict

OrderedDict ist eine Unterklasse von dict, die die Reihenfolge der eingefügten Elemente beibehält. Erstellen wir in ordered_dict.py ein OrderedDict und fügen einige Schlüssel-Wert-Paare hinzu:

from collections import OrderedDict

## Initialdefining OrderedDict
od = OrderedDict()

## Insert in key-value pairs
od['a'] = 1
od['b'] = 2
od['c'] = 3

## Iterate over the key-value pairs and print out the contents
for key, value in od.items():
    print(key, value)

Führen Sie dann das Skript im Terminal aus:

python ordered_dict.py

Ausgabe:

a 1
b 2
c 3

DefaultDict

Defaultdict(int)

DefaultDict ist eine Unterklasse von dict, die einen Standardwert für einen nicht existierenden Schlüssel liefert. Erstellen wir in default_dict1.py ein DefaultDict mit Standardwerten 0 und zählen die Vorkommen von Wörtern in einem Satz:

from collections import defaultdict

sentence = "the quick brown fox jumps over the lazy dog"
word_count1 = defaultdict(int)

for word in sentence.split():
    ## Zählt die Vorkommen von Wörtern
    word_count1[word] += 1

print(dict(word_count1))

Führen Sie dann das Skript im Terminal aus:

python default_dict1.py

Ausgabe:

{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

Wenn wir DefaultDict nicht verwendet hätten, würde der aufrufende Code so aussehen:

sentence = "the quick brown fox jumps over the lazy dog"
result = {}

for word in sentence.split():
    if word in result:
        result[word] += 1
    else:
        result[word] = 1

print(result)

Defaultdict(list)

Als nächstes erstellen wir in default_dict2.py ein DefaultDict mit Standardwerten [] und speichern die Anzahl in jedem Buchstaben:

from collections import defaultdict

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count2 = defaultdict(list)

for (key,value) in data:
    ## Speichert die Anzahl in jedem Buchstaben
    word_count2[key].append(value)

print(dict(word_count2))

Führen Sie dann das Skript im Terminal aus:

python default_dict2.py

Ausgabe:

{'a': [1, 1, 3], 'b': [1, 2, 3]}

Wenn wir DefaultDict nicht verwendet hätten, würde der aufrufende Code so aussehen:

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}

for (key, value) in data:
    if key in result:
        result[key].append(value)
    else:
        result[key] = [value]

print(result)

Defaultdict(set)

Schließlich erstellen wir in default_dict3.py ein DefaultDict mit Standardwerten set() und speichern die nicht wiederholte Anzahl in jedem Buchstaben:

from collections import defaultdict

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count3 = defaultdict(set)

for (key,value) in data:
    ## Speichert die nicht wiederholte Anzahl in jedem Buchstaben
    word_count3[key].add(value)

print(dict(word_count3))

Führen Sie dann das Skript im Terminal aus:

python default_dict3.py

Ausgabe:

{'a': {1, 3}, 'b': {1, 2, 3}}

Wenn wir DefaultDict nicht verwendet hätten, würde der aufrufende Code so aussehen:

data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}

for (key, value) in data:
    if key in result:
        result[key].add(value)
    else:
        result[key] = {value}

print(result)

Deque

Ein deque (doppelter Endpunkt-Warteschlange) ist eine Verallgemeinerung von Stacks und Queues, die schnelle O(1)-Append- und Pop-Operationen von beiden Enden unterstützt. Erstellen wir in deque.py ein deque und führen einige Operationen aus:

from collections import deque

d = deque([1, 2, 3, 4, 5])

## Anhängen rechts
d.append(6)
print("Append to the right:", d)

## Anhängen links
d.appendleft(0)
print("Append to the left:", d)

## Entfernen rechts
right_element = d.pop()
print("The right element:", right_element)
print("Pop from the right:", d)

## Entfernen links
left_element = d.popleft()
print("The left element:", left_element)
print("Pop from the left:", d)

## Drehen des deque
d.rotate(2)
print("Rotate clockwise the deque:", d)

d.rotate(-2)
print("Rotate counterclockwise the deque:", d)

Führen Sie dann das Skript im Terminal aus:

python deque.py

Ausgabe:

Append to the right: deque([1, 2, 3, 4, 5, 6])
Append to the left: deque([0, 1, 2, 3, 4, 5, 6])
The right element: 6
Pop from the right: deque([0, 1, 2, 3, 4, 5])
The left element: 0
Pop from the left: deque([1, 2, 3, 4, 5])
Rotate clockwise the deque: deque([4, 5, 1, 2, 3])
Rotate counterclockwise the deque: deque([1, 2, 3, 4, 5])

Zusammenfassung

In diesem Tutorial haben wir die Hauptklassen behandelt, die vom collections-Modul bereitgestellt werden, einschließlich namedtuple, Counter, OrderedDict, DefaultDict und deque. Diese Klassen können für verschiedene Aufgaben nützlich sein und sind tolle Ergänzungen zu Ihrem Python-Werkzeugkasten.