search
HomeBackend DevelopmentPython TutorialSummarize and organize! Summary of Python practical skills

This article brings you relevant knowledge about python, which mainly summarizes 24 very practical Python development skills, including all or any, bashplotlib, collections, etc. I hope it will help you Everyone is helpful.

Summarize and organize! Summary of Python practical skills

Recommended learning: python tutorial

In the process of learning Python, many friends may think, I have learned so much There are many, which ones are commonly used and practical? How to increase work efficiency?

Today, I have summarized 24 extremely useful Python practical skills. I hope it will be helpful to my friends! Huan Welcome to collect and learn, like and support. A technical exchange group is provided at the end of the article.

Here, I try to share some of these techniques in a format beginning with A - Z, and briefly introduce these methods. If you are interested in one or more of them, you can check the official website through the references at the end of the article. Documentation~

all or any

One of the many reasons why the Python language is so popular is because it is very readable and expressive.

People often joke that Python is executable pseudocode. It's hard to argue with that when you can write code like this.

x = [True, True, False]if any(x):
    print("至少有一个True")if all(x):
    print("全是True")if any(x) and not all(x):
    print("至少一个True和一个False")

bashplotlib

Have you ever thought about drawing graphics in the console?

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

# 模块安装
pip install bashplotlib
# 绘制实例
import numpy as np
from bashplotlib.histpgram import plot_hist
arr = np.ramdom.normal(size=1000, loc=0, scale=1)
plot_hist(arr, bincount=50)

collections

Python has some great default data types, but sometimes they don’t behave exactly the way you expect.

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

from collections import OrderedDict, Counter
# 记住键的添加顺序!
x = OrderedDict(a=1, b=2, c=3)
# 统计每个字符出现的频率
y = Counter("Hello World!")

dir

Ever wondered how to look inside a Python object and see what properties it has? At the command line, type:

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 working with. Read more about **functions****[2]** here.

emoji

emoji**[3]** is a visual emotional symbol used in wireless communications in Japan. Text refers to characters, which can be used to represent various expressions, such as smiley faces representing laughter, cakes representing food, etc. In mainland China, emojis are usually called "little yellow faces" or simply emojis.

# 安装模块
pip install emoji
# 做个尝试
from emoji import emojize
print(emojize(":thumbs_up:"))

from __future__ import

One of the popular results of Python is that there are always new versions being developed. New versions mean new features — unless your version is out of date.

But don’t worry. Using the __future__ module ****[4]** can help you import functionality with future versions of Python. It's literally like time travel or magic or something.

from __future__ import print_function
print("Hello World!")

geogy

Geography is a challenging field for most programmers. When obtaining geographical information or drawing maps, you will also encounter many problems. The **geopy module****[5]** makes geography-related content very easy.

pip install geopy

It works by abstracting the API of a range of different geocoding services. With 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 two locations in your preferred measurement units.

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

howdoi

When you use terminal programming, after encountering a problem, you will search for answers on StackOverflow, and then you will return to the terminal to continue programming. At this time, sometimes you don’t remember the solutions you found before. At this time, you need to check StackOverflow again, but you don’t want to leave the terminal. Then you need to use this useful command line toolhowdoi****[6 ].

pip install howdoi

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

howdoi vertical align css
howdoi for loop in java
howdoi undo commits in git

But be warned - it will scrape code from the top answers on StackOverflow. It may not always provide the most useful information...

howdoi exit vim

inspect

Python's **inspect module****[7]** is great for understanding What happens behind the scenes. You can even call its own methods!

The following code exampleinspect.getsource() is used to print your own source code. inspect.getmodule() Also used to print the module in which it is defined.

The last line of code prints its own line number.

import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)

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

Jedi

The Jedi library is an autocompletion 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 plugin. Luckily, there are already loads of this available!

**kwargs

在学习任何语言时,都会有许多里程碑。使用 Python 并理解神秘的**kwargs语法可能算作一个重要的里程碑。

字典对象前面的双星号****kwargs****[9]**允许你将该字典的内容作为命名参数传递给函数。

字典的键是参数名称,值是传递给函数的值。你甚至不需要调用它kwargs

dictionary = {"a": 1, "b": 2}def someFunction(a, b):
    print(a + b)
    return# 这些做同样的事情:someFunction(**dictionary)someFunction(a=1, b=2)

当你想编写可以处理未预先定义的命名参数的函数时,这很有用。

列表(list)推导式

关于 Python 编程,我最喜欢的事情之一是它的列表推导式****[10]

这些表达式可以很容易地编写非常顺畅的代码,几乎与自然语言一样。

numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 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 通过许多内置功能支持函数式编程。最有用的map()功能之一是函数——尤其是与**lambda 函数****[11]**结合使用时。

x = [1, 2, 3] 
y = map(lambda x : x + 1, x)
# 打印出 [2,3,4]
print(list(y))

在上面的示例中,map()将一个简单的 lambda 函数应用于x. 它返回一个映射对象,该对象可以转换为一些可迭代对象,例如列表或元组。

newspaper3k

如果你还没有看过它,那么准备好被Python newspaper module [12]模块震撼到。它使你可以从一系列领先的国际出版物中检索新闻文章和相关的元数据。你可以检索图像、文本和作者姓名。它甚至有一些内置的 NLP 功能**[13]**。

因此,如果你正在考虑在下一个项目中使用 BeautifulSoup 或其他一些 DIY 网页抓取库,使用本模块可以为你自己节省不少时间和精力。

pip install newspaper3k

Operator overloading

Python 提供对**运算符重载的****[14]**支持,这是让你听起来像一个合法的计算机科学家的术语之一。

这实际上是一个简单的概念。有没有想过为什么 Python 允许你使用+运算符来添加数字以及连接字符串?这就是操作符重载的作用。

你可以定义以自己的特定方式使用 Python 的标准运算符符号的对象。并且你可以在与你正在使用的对象相关的上下文中使用它们。

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  nothing
# False
something <h3 id="strong-pprint-strong"><strong>pprint</strong></h3><p>Python 的默认<code>print</code>函数完成了它的工作。但是如果尝试使用<code>print</code>函数打印出任何大的嵌套对象,其结果相当难看。这个标准库的漂亮打印模块**pprint****[15]**可以以易于阅读的格式打印出复杂的结构化对象。</p><p>这算是任何使用非平凡数据结构的 Python 开发人员的必备品。</p><pre class="brush:php;toolbar:false">import requests
import pprint
url = '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) 
<open></open>

这使得调试代码更加容易。将其添加到你的类定义中,如下所示:

class someClass: 
    def __repr__(self): 
        return "<some>"
someInstance = someClass()
# 打印 <some>
print(someInstance)</some></some>

sh

Python 是一种很棒的脚本语言。有时使用标准的 os 和 subprocess 库可能有点头疼。

该**SH库****[17]**让你可以像调用普通函数一样调用任何程序——对于自动化工作流和任务非常有用。

import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

Type hints

Python 是一种动态类型语言。定义变量、函数、类等时不需要指定数据类型。这允许快速的开发时间。但是,没有什么比由简单的输入问题引起的运行时错误更烦人的了。

Python 3.5**[18]** 开始,你可以选择在定义函数时提供类型提示。

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

你还可以定义类型别名。

from typing import List
Vector = List[float]
Matrix = List[Vector]
def addMatrix(a : Matrix, b : Matrix) -> Matrix:
  result = []
  for i,row in enumerate(a):
    result_row =[]
    for j, col in enumerate(row):
      result_row += [a[i][j] + b[i][j]]
    result += [result_row]
  return result
x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)

尽管不是强制性的,但类型注释可以使你的代码更易于理解。

它们还允许你使用类型检查工具,在运行前捕获那些杂散的 TypeError。如果你正在处理大型、复杂的项目,这是很有用的!

uuid

通过Python 标准库的 uuid 模块**[19]**生成通用唯一 ID(或“UUID”)的一种快速简便的方法。

import uuid
user_id = uuid.uuid4()
print(user_id)

这将创建一个随机的 128 位数字,该数字几乎肯定是唯一的。事实上,可以生成超过 2¹²² 种可能的 UUID。这超过了五个十进制 (或 5,000,000,000,000,000,000,000,000,000,000,000,000)。

在给定的集合中发现重复的概率极低。即使有一万亿个 UUID,重复存在的可能性也远低于十亿分之一。

Virtual environments

你可能同时在多个 Python 项目上工作。不幸的是,有时两个项目将依赖于相同依赖项的不同版本。你在你的系统上安装了什么?

幸运的是,Python支持对 虚拟环境**[20]** 的让你可以两全其美。从命令行:

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

现在,你可以在同一台机器上运行 Python 的独立版本和安装。

wikipedia

维基百科有一个很棒的 API,它允许用户以编程方式访问无与伦比的完全免费的知识和信息。在**wikipedia模块****[21]**使访问该API非常方便。

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

和真实站点一样,该模块提供了多语言支持、页面消歧、随机页面检索,甚至还有一个donate()方法。

xkcd

幽默是 Python 语言的一个关键特征,它是以英国喜剧小品剧**Python飞行马戏团****[22]**命名的。Python 的许多官方文档都引用了该节目最著名的草图。不过,Python 的幽默并不仅限于文档。试试运行下面的行:

import antigravity

YAML

YAML**[23]**指的是 “ 非标记语言” 。它是一种数据格式化语言,是 JSON 的超集。

与 JSON 不同,它可以存储更复杂的对象并引用它自己的元素。你还可以编写注释,使其特别适合编写配置文件。该**PyYAML模块****[24]**可让你使用YAML使用Python。

安装并然后导入到你的项目中:

pip install pyyamlimport yaml

PyYAML 允许你存储任何数据类型的 Python 对象,以及任何用户定义类的实例。

zip

压轴出场的也是很棒的一个模块。你曾经遇到过需要从两个列表中形成字典吗?

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

zip()内置函数需要一系列可迭代的对象,并返回一个元组列表中。每个元组按位置索引对输入对象的元素进行分组。

你还可以通过调用对象来“解压缩”对象*zip()

Python 是一种非常多样化且发展良好的语言,因此肯定会有许多我没有考虑的功能。如果你想了解更多的python模块,可以参考awesome-python****[25]

 推荐学习:python学习教程

The above is the detailed content of Summarize and organize! Summary of Python practical skills. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool