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

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the practical skills of Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

ALL OR ANY

One reason why Python has become such a popular language is that it is very readable and expressive. As a result, Python is often ridiculed as "executable pseudocode". If you don't believe it, look:

X = [True, True, False]

If any (x):

Print ("At least one True")

If all (x):

Print ("Not one False")

If any (x) and not all (x):

Print ("At least one True and one False")

BASHPLOTIB

Do you want to draw on the console?

$pip install bashplotlib

Now, you can have a picture in your console.

COLLECTIONS

Python has some great default data types, but sometimes they don't work the way you want them to.

Fortunately, the Python standard library provides the collection module. It allows you to use a wider variety of data types.

From collections import OrderedDict, Counter

# Remembers the order the keys are added!

X = OrderedDict (axi1, baux2, cyste3)

# Counts the frequency of each character

Y = Counter ("Hello World!")

DIR

In the face of a Python object, have you ever thought that you can see its properties directly? You might want to try the following code:

> > dir ()

> dir ("Hello World")

> dir (dir)

This is a very useful feature when running Python to dynamically explore the objects and modules you are using. More details can be found here: https://docs.python.org/3/library/functions.html#dir

EMOGI

That's right, you read it right!

$pip install emoji

Use python to create emojis, and so can you.

From emoji import emojize

Print (emojize (": thumbs_up:"))

FROM_GUTURE_IMPORT

Python is very popular, which causes its version to update very quickly, and new versions tend to have a lot of new features. If you don't update it, you can't use it.

However, don't be afraid. The _ _ future__ module allows you to import features from future versions. It's kind of like time travel!

From _ _ future__ import print_function

Print ("Hello World!")

GEOPY

Geography can be a very challenging area for programmers. However, the geopy module makes it very simple.

$pip install geopy

It works by extracting a range of api from different geocoding services, allowing you to get the full street address, latitude, longitude, and even elevation of a place.

It also contains a useful "distance" category. It can use the metric of your choice to calculate the distance between two locations.

From geopy import GoogleV3

Place = "221b Baker Street, London"

Location = GoogleV3 () .geocode (place)

Print (location.address)

Print (location.location)

HOWDOI

Sometimes you run into a programming problem and feel like you've seen the solution before, but you can't remember exactly what it's like. So you want to look on StackOverflow, but you don't want to leave the terminal. At this point, you need the following tool-- howdoi

$pip install howdoi

You can ask it any question you encounter, and it will try its best to give you an answer.

$howdoi vertical align css

$howdoi for loop in java

$howdoi undo commits in git

It's important to note that it only grabs the code from the answer at the top of StackOverflow. So it doesn't always give you the most useful information.

$howdoi exit vim

INSPECT

Python's inspect module is used to collect information about Python objects, to get information about the parameters of a class or function, source code, parsing stack, and so on.

The code sample below uses inspect.getsource () to print its own source code. Inspect.getmodule () is also used to print modules that define inspect.getmodule (). The last line of code prints the line number where the code is located. In this case, it is 4.

Import inspect

Print (inspect.getsource (inspect.getsource))

Print (inspect.getmodule (inspect.getmodule))

Print (inspect.currentframe () .f_lineno)

The inspect module can effectively let you know how your code works, and you can use it to complete some personal source code.

JEDI

The Jedi library is a library for automatic code completion and static analysis. It allows you to write code faster and more efficiently.

Unless you are developing your own editor, you may enjoy using Jedi as your editing plug-in.

You may already be using Jedi and just don't notice it. The IPython project uses Jedi to realize its automatic completion function.

* * KWARGS

No matter which language you learn, there are always some milestones along the way. Understanding the mysterious * * kwargs syntax should be an important milestone in Python programming learning.

Putting the double star "*" in front of the dictionary allows you to pass the contents of the dictionary to the function as a named parameter. The dictionary key is the name of the parameter, and the value of the key is passed to the function as the value of the parameter. As follows:

Dictionary = {"a": 1, "b": 2}

Def someFunction (a, b):

Print (a + b)

Return

# these do the same thing:

SomeFunction (* * dictionary)

SomeFunction (axi1, baux2)

When you want to create a function that needs to be able to handle parameters that have not been defined in advance, you need to use the techniques mentioned above.

LIST COMPREHENSIONS

List comprehensions (list derivation)

List derivation can be said to be one of my favorite Python techniques. This expression allows you to write code that is as easy to understand and concise as a natural language.

You can learn more about the use of list derivation through this link. Address: https://www.learnpython.org/en/List_Comprehensions

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 has many very useful built-in functions. One of them is map ()-- especially when combined with the lambda function.

X = [1, 2, 3]

Y = map (lambda x: X + 1, x)

# prints out [2,3,4]

Print (list (y))

In this example, map () applies a simple lambda function to each element in x. It returns a map object that can be converted into an iterable object, such as a list or tuple.

NEWSPAPER3K

Newspaper3k, if you haven't seen it yet, you may be amazed by this Python newspaper module.

It allows you to retrieve news and related metadata from a series of leading international publications. You can retrieve pictures, text and author names. It even has some built-in natural language processing capabilities. So, if you are considering using BeautifulSoup or other homemade crawler libraries for your next project. So, save time and energy, all you really need is $pip install newspaper3k.

OPERATOR OVERLOADING (operator overload)

Python supports operator overloading. Operator overloading is actually a simple concept. Have you ever wondered why Python allows you to use the "+" operator to implement both addition and connection strings? This is why operator overloading is at work.

You can define objects that use Python standard operator symbols, which allows you to use specific objects in a specific environment, as in the example below.

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.__value something = Thing(100) nothing = Thing(0) # True something >

Nothing

# False

Something

< nothing # Error something + nothing PPRINT Python的默认print函数可以满足日常的输出任务,但如果要打印更大的、嵌套式的对象,那么使用默认的print函数打印出来的内容会很丑陋。 这个时候我们就需要pprint了,它可以让复杂的结构型对象以可读性更强的格式显示。这对于经常要面对非普通数据结构的Python开发者来说是必不可少的工具。 import requests import pprint url = 'https://randomuser.me/api/?results=1' users = requests.get(url).json() pprint.pprint(users) QUEUE(队列) Python支持多线程,它是通过标准库中的Queue模块来实现的。这个模块可以让你实现队列数据结构。这种数据结构可以让你根据特定的规则添加和检索条目。 "先进先出"(FIFO)队列可以让你按照添加对象的顺序来检索他们。"后进先出"(LIFO)队列可以让你首先访问最近添加的对象。最后,优先队列可以让你根据他们排序的顺序进行检索。 _REPR_ 当你定义一个类的时候,提供一个方法可以返回用来表示该类对象的可打印字符串会非常有用。例如: >

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

> print (file)

This makes debug more convenient, which is defined as follows:

Class someClass:

Def _ repr__ (self):

Return ""

SomeInstance = someClass ()

# prints

Print (someInstance)

SH

The sh library allows you to call commands in the system as if you were calling a method.

Import sh

Sh.pwd ()

Sh.mkdir ('new_folder')

Sh.touch ('new_file.txt')

Sh.whoami ()

Sh.echo ('This is customers')

TYPE HINT (type hint)

Python is a dynamically typed language. When you define variables, functions, and categories, you do not need to specify the type of data. This can greatly improve your development speed, but it also comes at a cost. You may make a run error due to a simple input problem.

After Python3.5, this is not a problem, and you can choose whether or not to provide type hints when defining functions.

Def addTwo (x: Int)-> Int:

Return x + 2

You can also define aliases for types:

From typing import List

Vector = List [float]

Matrix = List [Vector]

Def addMatrix (a: Matrix, b: Matrix)-> Matrix:

Result = []

For iMagic 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)

Although not mandatory, type comments can make your code easier to understand. They also allow you to use type checking tools to catch these piecemeal type errors before running. If you are working on a large, complex project, type annotations may be very helpful

UUID

Through the uuid module in the Python standard library, a unified unique ID (also known as UUID) can be generated quickly and easily.

Import uuid

User_id = uuid.uuid4 ()

Print (user_id)

UUID is a 128-bit globally unique identifier, usually represented by a 32-byte string. It can guarantee the uniqueness of time and space, also known as GUID, the full name is: UUID-UUID in Universally Unique IDentifier,Python. It ensures the uniqueness of generating ID through MAC address, timestamp, namespace, random number and pseudo-random number.

VRITUAL ENVIRONMENTS

This is probably my favorite Python technique. You may often have to work on more than one Python project, but unfortunately, sometimes different projects rely on different versions of Python. Which version of Python should you install in your system at this time?

Fortunately, Python can support the establishment of different virtual environments to meet the needs of different versions.

Python-m venv my-project

Source my-project/bin/activate

Pip install all-the-modules

Now you can install and run separate versions of Python on a single machine. great!

WIKIPEDIA

Wikipedia has a great API that allows users to programmatically access Wikipedia entries. Using the wikipedia module in Python allows you to access the API in the most convenient way.

Import wikipedia

Result = wikipedia.page ('freeCodeCamp')

Print (result.summary)

For link in result.links:

Print (link)

Like real sites, the module supports multiple languages, page disambiguation, random page retrieval, and even the donate () method.

YAML

YAML is a foreign language abbreviation for "YAML is not a markup language". It is a data format language and is the parent set of JSON. Unlike JSON, it can store more complex objects and can reference its own elements. You can also write comments, which makes YAML particularly suitable for writing configuration files.

The PyYAML module allows you to call YAML using Python. Install using the following statement:

$pip install pyyaml

Then import it into the project:

Import yaml

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

ZIP

The last technique is also very cool. Have you ever wanted to map the elements in two lists one by one and combine them into dictionaries? Then you should use zip.

Keys = ['await,' baked,'c']

Vals = [1,2,3]

Zipped = dict (zip (keys, vals))

The built-in function zip () takes several iterable objects and returns a list of multiple tuples. Each tuple groups its elements according to the location index of the input object. You can also use * zip () to "extract" the object.

This is the end of the content of "what are the practical skills of Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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