Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills to use Python?

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the easy-to-use Python skills". In the daily operation, I believe that many people have doubts about the easy-to-use Python skills. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "easy-to-use Python skills." Next, please follow the editor to study!

1. Introduction

This article is a sharing of some useful tips in the Python ecosystem. Most techniques only use packages from the standard library, but others involve third-party packages.

Before we start reading this article, let's review the concept of Iterables in Python.

According to the Python standards documentation, the concepts of Iterable are as follows:

An object that can return one member at a time.

Examples of iterables include:

The _ _ iter__ () method is defined in the implementation of all sequence types (such as list, str, and tuple) and some non-sequence types, such as dict, file objects, and classes

Iterables is a concept that we need to keep in mind, because many of the techniques we demonstrate next use the itertools package.

The itertools module provides functions for receiving Iterable objects, rather than just printing one object at a time.

2.Trick 1

In our work and study, we often need to use a simple function to generate a new list,set or dict from a list. At this point we will use the concept of iterables.

For example:

Generate List:

Names = ['John',' Bard', 'Jessica'' Andres'] lower_names = [name.lower () for name in names]

Generate Set:

Names = ['John',' Bard', 'Jessica'' Andres'] lower_names = {name.lower () for name in names}

Generate Dict:

Names = ['John',' Bard', 'Jessica'' Andres'] lower_names = {name:name.lower () for name in names}

Personal advice:

Used only when the number of for statements, function calls, and method calls is small.

3.Trick 2

Sometimes we need to get all the possible combinations between two list objects.

The first implementation that comes to mind may be as follows:

L1 = [1,2,3] L2 = [4,5,6] combinations = [] for E1 in L1: for e2 in L2: combinations.append ((E1, e2))

Or simplify it as follows:

Combinations = [(E1, e2) for E1 in L1 for e2 in L1]

The above implementation is concise, but the standard library itertools provides the product function, which provides the same results. As follows:

From itertools import productl1 = [1,2,3] L2 = [4,5,6] combinatios = product (L1, L2) 4.Trick3

Suppose there is a list of elements, and we need to compare or apply some actions between each pair of adjacent elements, which is sometimes called a sliding window of two elements. We can do this in the following ways:

From itertools import teefrom typing import Iterabledef window2 (iterable: Iterable): it, offset = tee (iter (iterable)) next (offset) return zip (it, offset) l = [1,2,3,4,5,6] dd = window2 (l) for an in dd: print (a)

The running results are as follows:

(1,2) (2,3) (3,4) (4,5) (5,6) 5.Trick4

Sometimes we need a class to store information, but if we find it too troublesome to create a class and define its _ _ init__ () function, we might as well choose to use dataclass. As follows:

From dataclasses import dataclass@dataclassclass Person: name: str age: int address: str

The above code creates a class with a default constructor that receives the assignment of the corresponding field in the same order as the declaration.

Person = Person (name='John', age=12, address='nanjing street')

Another advantage of dataclass is that special methods, such as _ _ str__, repr, _ _ eq__, and so on, are generated by default. For more information about the use of dataclass, please refer to the official website.

It is worth mentioning that the type comments (str, int, and so on) of the member variables we declare in the class do not force the values passed in the constructor to be of this type. That is, dataclasses does not perform data type checking when constructing objects.

6.Trick5

We sometimes want to think of an operation on an object as an operation on tuple. One option is to use collections.namedtuple, but there is also an implementation that is more similar to dataclass. As follows:

From typing import NamedTupleclass Coordinate (NamedTuple): X: int y: int

A standard class defined above can be used as a tuple, as follows:

Coordinate = Coordinate (10,15) coordinate.x = = coordinate [0] / / True coordinate.y = = coordinate [1] / / True7.Trick6

If we have a dataclass, we need to verify that the input data conforms to the type annotation. In this case, install the third-party software package pydantic and set the

Replace from dataclasses import dataclass with from pydantic.dataclasses import dataclass, as follows:

From pydantic.dataclasses import dataclass@dataclassclass Person: name: str age: int address: str

This generates a class with parsing and type validation of input data based on the type declared by the member variable. Pydantic enforces type prompts at run time and provides friendly error reminders when the data is invalid.

8.Trick7

In some cases, we need to generate some basic statistics about the frequency of the elements in the container. In this case, you can use the standard structure Counter to receive the iterable and generate statistics based on the frequency of the element.

From collections import Counterl = [1,1,2,3,4,4] frequencys = Counter (l) print (frequencys [1]) / / Ouput: 2print (frequencys [2]) / / Ouput: 1print (frequencys [2323]) / / Ouput: 0

Counter also provides other methods, such as most_common, for retrieving the most common elements.

9.Trick8

If we do the corresponding function processing relative to the two elements in the list, the easiest way to think of is as follows:

L1 = [1,2,3] L2 = [4,5,6] for (E1, e2) in zip (L1, L2): F (E1, e2)

But using the function map can make the code a little more concise.

L1 = [1,2,3] L2 = [4,5,6] map (f, L1, L2) 10.Trick9

Sometimes we need to randomly select an element from a list, and then we use random.choice. As follows:

From random import choicel = [1,2,3] random = choice (l)

What if we need to select multiple elements at random? Using random.choices, of course.

From random import choicesl = [1, 2, 3, 4, 5] random_elements = choices (l, KF3)

The parameter k in the above code is the number of elements we randomly select.

At this point, the study of "what are the easy-to-use Python skills" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report