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 practical skills of Python and how to use them

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

Share

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

Today, I would like to share with you what Python practical skills are and how to use the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.

All or any

One of the many reasons why Python is so popular is that it is readable and expressive.

People often joke that Python is executable pseudocode. When you can write code like this, it's hard to refute.

X = [True, True, False] if any (x): print ("at least one True") if all (x): print ("all True") if any (x) and not all (x): print ("at least one True and one False") bashplotlib

Have you ever thought of drawing graphics in the console?

Bashplotlib is a Python library that can help us draw data on the command line (rough environment).

# Module installs pip install bashplotlib# drawing instance import numpy as npfrom bashplotlib.histpgram import plot_histarr = np.ramdom.normal (size=1000, loc=0, scale=1) plot_hist (arr, bincount=50) collections

Python has some great default data types, but sometimes their behavior doesn't exactly match your expectations.

Fortunately, the Python standard library provides the collections module * * [1] * *. This convenient add-on provides you with more data types.

From collections import OrderedDict, Counter# remember the order in which keys are added! X = OrderedDict (axi1, bread2, cymb3) # count the frequency of each character y = Counter ("Hello World!") dir

Have you ever thought about how to look inside a Python object and see what properties it has? On the command line, enter:

Dir () dir ("Hello World") dir (dir)

This can be a very useful feature when running Python interactively and dynamically exploring the objects and modules you are using. Read more about functions**** [2] * * here.

Emoji

Emoji** [3] * * is a visual emotion symbol used in wireless communication in Japan, drawing refers to pictures, and text refers to characters, which can be used to represent a variety of expressions, such as smiling face, cake representing food, and so on. On Chinese mainland, emoji is usually called "Little Yellow face", or emoji.

# try to install the module pip install emoji# from emoji import emojizeprint (emojize (": thumbs_up:") from _ _ future__ import

One of the results of Python popularity is that there is always a new version under development. A new version means new features-unless your version is out of date.

But don't worry. Using this * * _ future__ module * * [4] * * can help you use the import function of future versions of Python. Literally, it's like time travel, magic or something.

From _ _ future__ import print_functionprint ("Hello World!") geogy

Geography is a challenging field for most programmers. There are also a lot of problems in obtaining geographic information or drawing maps. This * * geopy module * [5] * * makes geography-related content very easy.

Pip install geopy

It works by abstracting the API of a series of different geocoding services. Through it, you can get the complete street address, latitude, longitude and even altitude of a place.

There is also a useful distance class. It calculates the distance between the two positions in your preferred unit of measurement.

From geopy import GoogleV3place = "221b Baker Street, London" location = GoogleV3 () .geocode (place) print (location.address) print (location.location) howdoi

When you use terminal terminal programming, by searching for answers on StackOverflow after you encounter a problem, and then go back to the terminal to continue programming, sometimes you don't remember the solution you found before, and you need to re-check StackOverflow, but you don't want to leave the terminal, then you need to use this useful command line tool howdoi**** [6].

Pip install howdoi

No matter what question you have, you can ask it and it will try its best to reply.

Howdoi vertical align csshowdoi for loop in javahowdoi undo commits in git

Note, though-- it grabs the code from StackOverflow's best answer. It may not always provide the most useful information...

Howdoi exit viminspect

Python's * * inspect module * [7] * * is perfect for understanding what's going on behind the scenes. You can even call its own methods!

The following code example inspect.getsource () is used to print your own source code. Inspect.getmodule () is also used to print the module that defines it.

The last line of code prints its own line number.

Import inspectprint (inspect.getsource (inspect.getsource)) print (inspect.getmodule (inspect.getmodule)) print (inspect.currentframe () .f_lineno)

Of course, in addition to these trivial uses, the inspect module can prove useful in understanding what your code is doing. You can also use it to write self-documenting code.

Jedi

The Jedi library is an autocomplete and code analysis library. It makes writing code faster and more efficient.

Unless you are developing your own IDE, you may be interested in using Jedi * * [8] * * as an editor plug-in. Fortunately, there is already a load available!

* * kwargs

There are many milestones when learning any language. Using Python and understanding the mysterious * * kwargs syntax may count as an important milestone.

The double asterisk in front of the dictionary object * kwargs**** [9] * * allows you to pass the contents of the dictionary to the function as a named argument.

The key of the dictionary is the parameter name, and the value is the value passed to the function. You don't even need to call it kwargs!

Dictionary = {"a": 1, "b": 2} def someFunction (a, b): print (a + b) return# do the same thing: someFunction (* * dictionary) someFunction (axi1, baked 2)

This is useful when you want to write functions that handle named parameters that are not predefined.

List (list) derivation

One of my favorite things about Python programming is its list-driven [10].

These expressions can be easily written in very smooth code, almost like a natural language.

Numbers = [1city 2 is 3 city 4 5 is 7] evens = [x for x in numbers if x% 2 city 0] odds = [y for y in numbers if y not in evens] cities = ['London',' Dublin', 'Oslo'] def visit (city): print ("Welcome to" + city) for city in cities: visit (city) map

Python supports functional programming through many built-in features. One of the most useful map () functions is the function-- especially when used in conjunction with the * * lambda function * * [11] * *.

X = [1,2jue 3] y = map (lambda x: X + 1, x) # print out [2Jing 3pm 4] print (list (y))

In the above example, map () applies a simple lambda function to x. It returns a mapping object that can be converted to iterable objects, such as lists or tuples.

Newspaper3k

If you haven't seen it yet, be prepared to be shocked by the Python newspaper module [12] module. It allows you to retrieve news articles and related metadata from a range of leading international publications. You can retrieve images, text and author names. It even has some built-in NLP functions * * [13] * *.

Therefore, if you are considering using BeautifulSoup or some other DIY web page crawl libraries in your next project, using this module can save yourself a lot of time and effort.

Pip install newspaper3kOperator overloading

Python provides * * operator overloading support, which is one of the terms that makes you sound like a legitimate computer scientist.

This is actually a simple concept. Have you ever wondered why Python allows you to use the + operator to add numbers and connection strings? This is what operator overloading is for.

You can define objects that use Python's standard operator symbols in your own way. And you can use them in the context of the objects you are using.

Class Thing: def _ init__ (self, value): self.__value = value def _ gt__ (self, other): return self.__value > other.__value def _ lt__ (self, other): return self.__value

< other.__valuesomething = Thing(100)nothing = Thing(0)# Truesomething >

Nothing# Falsesomething

< nothing# Errorsomething + nothingpprint Python 的默认print函数完成了它的工作。但是如果尝试使用print函数打印出任何大的嵌套对象,其结果相当难看。这个标准库的漂亮打印模块**pprint****[15]**可以以易于阅读的格式打印出复杂的结构化对象。 这算是任何使用非平凡数据结构的 Python 开发人员的必备品。 import requestsimport pprinturl = 'https://randomuser.me/api/?results=1'users = requests.get(url).json()pprint.pprint(users)Queue Python 标准库的 Queue 模块实现支持多线程。这个模块让你实现队列数据结构。这些是允许你根据特定规则添加和检索条目的数据结构。 "先进先出"(FIFO)队列让你可以按添加顺序检索对象。"后进先出"(LIFO) 队列让你可以首先访问最近添加的对象。 最后,优先队列让你可以根据对象的排序顺序检索对象。 这是一个如何在 Python 中使用队列**Queue****[16]**进行多线程编程的示例。 __repr__ 在 Python 中定义类或对象时,提供一种将该对象表示为字符串的"官方"方式很有用。例如: >

> > file = open ('file.txt', 'r') > print (file)

This makes debugging code easier. Add it to your class definition, as follows:

Class someClass: def _ _ repr__ (self): return "" someInstance = someClass () # print print (someInstance) sh

Python is a great scripting language. Sometimes using standard os and subprocess libraries can be a bit of a headache.

The * * SH library * [17] * * allows you to call any program like a normal function-very useful for automating workflows and tasks.

Import shsh.pwd () sh.mkdir ('new_folder') sh.touch (' new_file.txt') sh.whoami () sh.echo ('This is girls') Type hints

Python is a dynamically typed language. You do not need to specify a data type when defining variables, functions, classes, and so on. This allows for fast development time. However, there is nothing more annoying than run-time errors caused by simple input problems.

Starting with Python 3.5 hints * [18] * *, you can choose to provide type hints when defining functions.

Def addTwo (x: Int)-> Int: return x +

You can also define type aliases.

From typing import ListVector = list [float] Matrix = list [vector] def addMatrix (a: Matrix, b: Matrix)-> Matrix: result = [] for iLeary in enumerate (a): result_row = [] for j, col in enumerate (row): result_row + = [a [I] [j] + b [I] [j]] result + = [result_row] return resultx = [1.0,0.0], [0.0] 1]] y = [[2.0,1.0], [0.0,2.0]] z = addMatrix (x, y)

Although not mandatory, type comments can make your code easier to understand.

They also allow you to use type checking tools to capture stray TypeError before running. This is useful if you are working on large, complex projects!

Uuid

A quick and easy way to generate a universal and unique ID (or "UUID") through the uuid module of the Python standard library.

Import uuiduser_id = uuid.uuid4 () print (user_id)

This creates a random 128-digit number that is almost certainly unique. In fact, more than 2 possible UUID can be generated. This exceeds five decimal systems (or 50000000000000000000000000000000000).

The probability of finding repetition in a given set is extremely low. Even with a trillion UUID, the likelihood of repetition is far less than 1/1000000000.

Virtual environments

You may be working on multiple Python projects at the same time. Unfortunately, sometimes two projects will rely on different versions of the same dependency. What have you installed on your system?

Fortunately, Python supports virtual environments so that you can have the best of both worlds. From the command line:

Python-m venv my-project source my-project/bin/activate pip install all-the-modules

Now you can run a separate version and installation of Python on the same machine.

Wikipedia

Wikipedia has a great API that allows users to programmatically access unparalleled and completely free knowledge and information. In the * * wikipedia module * * [21] * *, it is very convenient to access the API.

Import wikipediaresult = wikipedia.page ('freeCodeCamp') print (result.summary) for link in result.links: print (link)

Like real sites, this module provides multilingual support, page disambiguation, random page retrieval, and even a donate () method.

Xkcd

Humor is a key feature of the Python language. It is named after the British comedy sketch Python flying circus. Many of Python's official documents refer to the show's most famous sketches. However, Python's humor is not limited to documents. Try running the following line:

Import antigravityYAML

YAML** [23] * * refers to "non-markup language". It is a data formatting language and a superset of JSON.

Unlike JSON, it can store more complex objects and reference its own elements. You can also write comments to make them particularly suitable for writing configuration files. The * * PyYAML module * [24] * * allows you to use YAML and Python.

Install and then import into your project:

Pip install pyyamlimport yaml

PyYAML allows you to store Python objects of any data type, as well as instances of any user-defined class.

Zip

The finale is also a great module. Have you ever encountered the need to form a dictionary from two lists?

Keys = ['averse,' baked,'c'] vals = [1,2,3] zipped = dict (zip (keys, vals))

The zip () built-in function requires a series of iterating objects and returns a list of tuples. Each tuple groups the elements of the input object by location index.

You can also "unzip" the object * zip () by calling the object.

These are all the contents of this article entitled "what are the practical skills of Python and how to use them?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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