ANI

Amazing things you can do with Python's collection module module

Amazing things you can do with Python's collection module module
Photo for Editor | Chatgt

Introduction

The Normal Python Library is broad, offers various modules to perform regular activities properly.

Between this, collections Module is an example of standing, which provides special types of data that can serve as other ways in the common Python articles built in dict, list, setbeside tuple. While many developers are familiar with other elements, the module holds various unusual items and incorporating the code, improving the readable, and enhancement.

This lesson tests ten helpful – and maybe we are surprising – Python use collections Module.

1. Calculated inactive things inactive with counter

The most common work is about any data analysis project lists things for things respectively. This page collections.Counter The class is specifically designed for this. It is a subclass dictionary when things are kept as their calculations are stored as prices.

from collections import Counter

# Count the frequency of words in a list
words = ['galaxy', 'nebula', 'asteroid', 'comet', 'gravitas', 'galaxy', 'stardust', 'quasar', 'galaxy', 'comet']
word_counts = Counter(words)

# Find the two most common words
most_common = word_counts.most_common(2)

# Output results
print(f"Word counts: {word_counts}")
print(f"Most common words: {most_common}")

Which is output:

Word counts: Counter({'galaxy': 3, 'comet': 2, 'nebula': 1, 'asteroid': 1, 'gravitas': 1, 'stardust': 1, 'quasar': 1})
Most common words: [('galaxy', 3), ('comet', 2)]

2. Creating Clean Classes with namedtuple

When you need a simple category of planning data, without any means, a namedtuple It is a useful way, working with memory. Allows you to create things such as tuple – such as the stadiums accessible by looking at attribute and becoming index and evident. This makes your code learned more than using normal tendency.

from collections import namedtuple

# Define a Book namedtuple
# Fields: title, author, year_published, isbn
Book = namedtuple('Book', ['title', 'author', 'year_published', 'isbn'])

# Create an instance of the Book
my_book = Book(
    title="The Hitchhiker"s Guide to the Galaxy',
    author="Douglas Adams",
    year_published=1979,
    isbn='978-0345391803'
)

print(f"Book Title: {my_book.title}")
print(f"Author: {my_book.author}")
print(f"Year Published: {my_book.year_published}")
print(f"ISBN: {my_book.isbn}")

print("n--- Accessing by index ---")
print(f"Title (by index): {my_book[0]}")
print(f"Author (by index): {my_book[1]}")
print(f"Year Published (by index): {my_book[2]}")
print(f"ISBN (by index): {my_book[3]}")

Which is output:

Accessing book data by field name
Title (by field name): The Hitchhiker's Guide to the Galaxy
Author (by field name): Douglas Adams
Year Published (by field name): 1979
ISBN (by field name): 978-0345391803

Accessing book data by index
Title (by index): The Hitchhiker's Guide to the Galaxy
Author (by index): Douglas Adams
Year Published (by index): 1979
ISBN (by index): 978-0345391803

You can imagine with namedtuple Like the same Corm of the C consists of, or as a data category without the methods. They are definitely used.

3. Managing unethical dictionary buttons with defaultdict

Common frustration when working with dictionaries are the KeyError That happens when you try to access the missing key. This page collections.defaultdict The correct solution. It is less than dict That costs the factory work to provide automatic number of key keys. This is very effective in the separating things.

from collections import defaultdict

# Group a list of tuples by the first element
scores_by_round = [('contestantA', 8), ('contestantB', 7), ('contestantC', 5),
                   ('contestantA', 7), ('contestantB', 7), ('contestantC', 6),
                   ('contestantA', 9), ('contestantB', 5), ('contestantC', 4)]
grouped_scores = defaultdict(list)

for key, value in scores_by_round:
    grouped_scores[key].append(value)

print(f"Grouped scores: {grouped_scores}")

Which is output:

Grouped scores: defaultdict(, {'contestantA': [8, 7, 9], 'contestantB': [7, 7, 5], 'contestantC': [5, 6, 4]})

4. Using quick and stacks with deque

Python list can be used as stacks and lines, even if it is not designed for these activities. Installing and exiting from the end of the list is fast, but do the same from the beginning is slowly because all other things should be changed. This page collections.deque (Double-headed line) for quick interest and popps from both ends.

First, here is a line example using deque.

from collections import deque

# Create a queue
d = deque([1, 2, 3])
print(f"Original queue: {d}")

# Add to the right
d.append(4)
print("Adding item to queue: 4")
print(f"New queue: {d}")

# Remove from the left
print(f"Popping queue item (from left): {d.popleft()}")  

# Output final queue
print(f"Final queue: {d}")

& Nbsp

Which is output:

Original queue: deque([1, 2, 3])
Adding item to queue: 4
New queue: deque([1, 2, 3, 4])
Popping queue item (from left): 1
Final queue: deque([2, 3, 4])

And now let's use deque To build a stack:

from collections import deque

# Create a stack
d = deque([1, 2, 3])
print(f"Original stack: {d}")

# Add to the right
d.append(5)
print("Adding item to stack: 5")
print(f"New stack: {d}")

# Remove from the right
print(f"Popping stack item (from right): {d.pop()}")

# Output final stack
print(f"Final stack: {d}")

Which is output:

Original stack: deque([1, 2, 3])
Adding item to stack: 5
New stack: deque([1, 2, 3, 5])
Popping stack item (from right): 5
Final stack: deque([1, 2, 3])

5. Remembering in the order of installation with OrderedDict

Before Python 3.7, general dictionaries did not maintain the order of the material. Solve this, the collections.OrderedDict was used. While regular texts now keep input order, OrderedDict You still have different features, such as move_to_end() The way, useful for activities such as building a simple cache.

from collections import OrderedDict

# An OrderedDict remembers the order of insertion
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3

print(f"Start order: {list(od.keys())}")

# Move 'a' to the end
od.move_to_end('a')
print(f"Final order: {list(od.keys())}")

Which is output:

Start order: ['a', 'b', 'c']
Final order: ['b', 'c', 'a']

6. To join the many dictionaries with ChainMap

This page collections.ChainMap The class provides a way to link many dictionaries together to be treated as one unit. It is usually more faster than creating a new dictionary and running more update() Calls. Looking at the lower mappings individually until the key is found.

Let's build a chainmap named named the name and returns the keys.

from collections import ChainMap

# Create dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Create a ChainMap
chain = ChainMap(dict1, dict2)

# Print dictionaries
print(f"dict1: {dict1}")
print(f"dict2: {dict2}")

# Query ChainMap for keys and return values
print("nQuerying ChainMap for keys")
print(f"a: {chain['a']}")
print(f"c: {chain['c']}")
print(f"b: {chain['b']}")

Which is output:

dict1: {'a': 1, 'b': 2}
dict2: {'b': 3, 'c': 4}

Querying keys for values
a: 1
c: 4
b: 2

Note that in this above case, 'B' is first found dict1The first dictionary in the chainand therefore the amount associated with this restored button.

7. To keep the limited history of Dumbe's maxlen

A deque can be created in the formal length of the edited using maxlen the argument. If many things are added than a big length, things from opposite end is automatically lost. This is ready to keep the history of things n.

from collections import deque

# Keep a history of the last 3 items
history = deque(maxlen=3)
history.append("cd ~")
history.append("ls -l")
history.append("pwd")
print(f"Start history: {history}")

# Add a new item, push out the left-most item
history.append("mkdir data")
print(f"Final history: {history}")

Which is output:

Start history: deque(['cd ~', 'ls -l', 'pwd'], maxlen=3)
Final history: deque(['ls -l', 'pwd', 'mkdir data'], maxlen=3)

8. Building the easiest dictionaries with defaultdict

Building in the defaultdictYou can create dictionaries or such as trees easily. By giving a lambda The work that returns another defaultdictYou can create dictionary dictionaries in flies.

from collections import defaultdict
import json

# A function that returns a defaultdict
def tree():
    return defaultdict(tree)

# Create a nested dictionary
nested_dict = tree()
nested_dict['users']['user1']['name'] = 'Felix'
nested_dict['users']['user1']['email'] = '[email protected]'
nested_dict['users']['user1']['phone'] = '515-KL5-5555'

# Output formatted JSON to console
print(json.dumps(nested_dict, indent=2))

Which is output:

{
  "users": {
    "user1": {
      "name": "Felix",
      "email": "[email protected]",
      "phone": "515-KL5-5555"
    }
  }
}

9. To perform arithmetic duties on Counters

News Flash: You can do arithmetic duties, such as added, to remove, cohesion, and the union, in the Counter things. This is a powerful comparative tool and combining the frequency calculation from different sources.

from collections import Counter

c1 = Counter(a=4, b=2, c=0, d=-2)
c2 = Counter(a=1, b=2, c=3, d=4)

# Add counters -> adds counts for common keys
print(f"c1 + c2 = {c1 + c2}")

# Subtract counters -> keeps only positive counts
print(f"c1 - c2 = {c1 - c2}")

# Intersection -> takes minimum of counts
print(f"c1 & c2 = {c1 & c2}")

# Union -> takes maximum of counts
print(f"c1 | c2 = {c1 | c2}")

Which is output:

c1 + c2 = Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2})
c1 - c2 = Counter({'a': 3})
c1 & c2 = Counter({'b': 2, 'a': 1})
c1 | c2 = Counter({'a': 4, 'd': 4, 'c': 3, 'b': 2})

10. Rounding traveling things with deque

This page deque thing has a a rotate() How they allow you to rotate things well. The positive argument ranges things on the right; right, left. This is too fast than light and joining a list or tuples.

from collections import deque

d = deque([1, 2, 3, 4, 5])
print(f"Original deque: {d}")

# Rotate 2 steps to the right
d.rotate(2)
print(f"After rotating 2 to the right: {d}")

# Rotate 3 steps to the left
d.rotate(-3)
print(f"After rotating 3 to the left: {d}")

Which is output:

Original deque: deque([1, 2, 3, 4, 5])
After rotating 2 to the right: deque([4, 5, 1, 2, 3])
After rotating 3 to the left: deque([2, 3, 4, 5, 1])

Rolling up

This page collections Module in Python is a set of special Datatypes, top working work. From counting things with Counter Building in active lines with dequeThese tools can make your code clean, efficient, and more than the Pythonic. By adapting these amazing and powerful aspects, you can solve the common problems of planning and effective way.

Matthew Mayo (@ mattma13) Holds the Master graduation in computer science and diploma graduated from the data mines. As the administrative editor of Kdnuggets & State, as well as a machine that does chinle in the Mastery learner, Matthew aims to make complex concepts of data science accessible. His technological interests include chronology, language models, studys of the machine, and testing ai. It is conducted by the purpose of democracy in the data science. Matthew has been with codes since he was 6 years old.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button