Python Basics Dry 02

Source: Internet
Author: User
Tags first string

List and tuple

List-like arrays

A tuple is the same as a list, but once defined, the contents of the inside cannot be changed.

In this way, the above content can not be changed.

"Variable" tuple, does not mean that a tuple can not be changed?

Want memory

Dict and set

Dict is a python built-in dictionary that is called map in other languages and is stored using key-value (Key-value), which has a very fast lookup speed.

There is no sequential relationship in the Dict.

Compared with list, Dict has the following features:

1. The search and insertion speed is very fast and will not slow with the increase of key

2. Need to occupy a lot of memory, memory waste more

And the list is the opposite:

1. The time to find and insert increases as the element increases

2. Small footprint, Little wasted memory

So, Dict is a way of exchanging space for time.

Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object.

This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating position by key is called hash Algorithm (hash)

To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be a key.

Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

To create a set, you need to provide a list as the input collection:

Note that the parameter passed in [1, 2, 3] is a list, and the display {1, 2, 3} only tells you that the set has 3 elements, the order of the display does not indicate that the set is ordered.

b = A.replace (' A ', ' a ')

Always keep in mind that a it is a variable, but a ‘abc‘ string Object! Sometimes, we often say that the object's a content is ‘abc‘ , but actually refers to, a itself is a variable, it points to the content of the object is ‘abc‘ :

When we call a.replace(‘a‘, ‘A‘) , the actual invocation method replace is on the string object ‘abc‘ , and although the method is called, it replace does not change ‘abc‘ the contents of the string. Instead, the replace method creates a new string ‘Abc‘ and returns, and if we point to the new string with a variable, b it's easy to understand that the variable a still points to the original string ‘abc‘ , but the variable points to the b new string ‘Abc‘ :

Function

can return multiple values (actually a tuple)

Default parameters for pits

First define a function, pass in a list, add one and END return:

When you call normally, the result looks good.

When you use the default parameter call, the result is also right at the beginning

However, when called again add_end() , the result is incorrect.

Many beginners are puzzled, the default argument is [] , but the function seems to "remember" the last time the list was added ‘END‘

The reasons are explained as follows:

When the Python function is defined, the value of the default parameter is L calculated, that is [] , because the default parameter L is also a variable, which points to the object [] , each time the function is called, if the change L of content, the next call, the contents of the default parameters will change,

is no longer the function definition [] .

So, one thing to keep in mind when defining default parameters: The default argument must point to the immutable object

To modify the example above, we can use None this invariant object to implement

Why design str , None such an immutable object? Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the object is read simultaneously in a multitasking environment

No need to lock, and read a little problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.

Variable parameters

Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged, but when the function is called, you can pass in any parameter, including 0 parameters:

What if you have a list or a tuple and you want to invoke a mutable parameter? Can do this

This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with a * number, the list or the elements of a tuple into a variable parameter to pass in

*numsIndicates that nums all elements of this list are passed in as mutable parameters. This writing is quite useful and very common

Keyword parameter: **kw, turn the parameter into a dict.

Parameter combinations

To define a function in Python, you can use the required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, which can all be combined using 5 parameters. Note, however, that the order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.

The most amazing thing is that through a tuple and dict, you can also call the above function:

There seems to be a problem with the parameter passing.

Be aware of the syntax for defining mutable parameters and keyword parameters:

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, kw receives a dict.

Module

Benefits of the module:

The greatest benefit is that the maintainability of the code is greatly improved. Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.

You may also think, what if different people write the same module name? To avoid module name collisions, Python introduces a way to organize modules by directory, called packages

For example, a abc.py file is a named abc module, and a file is a named xyz.py xyz module

Now, assuming that our abc and xyz these two module names conflict with the other modules, we can organize the modules through the package to avoid conflicts. Method is to select a top-level package name, for example mycompany , in the following directory to store

Once the package is introduced, all modules will not conflict with others as long as the package name in the top layer does not conflict with others. Now, the name of the abc.py module becomes mycompany.abc , similarly, xyz.py the module name becomes mycompany.xyz .

Please note that each package directory will have a __init__.py file that must exist, otherwise Python will use this directory as a normal directory, not a package. __init__.pycan be an empty file, or it can have Python code,

Because __init__.py itself is a module, and its module name ismycompany

Lines 1th and 2nd are standard comments, and the 1th line of comments allows the hello.py file to run directly on Unix/linux/mac, and the 2nd line comment indicates that the. py file itself uses standard UTF-8 encoding;

Line 4th is a string representing the document comment of the module, and the first string of any module code is treated as a document comment of the module;

The 6th line uses __author__ variables to write the author in, so that when you open the source code, others will be able to admire your name;

The above is the Python module standard file template, of course, you can also delete all do not write, but, according to the standard is certainly true

After the module is imported, sys we have a variable to sys point to the module, and with sys this variable, we can access sys all the functions of the module

sysThe module has a argv variable that stores all the parameters of the command line with the list. argvthere is at least one element, because the first parameter is always the name of the. py file, for example:

python3 hello.pythe operation obtained sys.argv is[‘hello.py‘]

python3 hello.py Michaelthe operation obtained sys.argv is [‘hello.py‘, ‘Michael] .

Finally, notice that the two lines of code

When we run the module file (itself) at the command line, the hello Python interpreter places a special variable __name__ __main__ , and if the module is imported elsewhere, the hello if judgment will fail, so this if test can make a module

Executing some extra code from the command-line runtime is the most common way to run tests.

Scope

In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done by a _ prefix.

Normal functions and variable names are public and can be referenced directly, such as: abc , x123 , PI etc.

__xxx__Such variables are special variables, can be directly referenced, but there are special purposes, such as the above __author__ , __name__ is a special variable, hello the module definition of the document can also be accessed with special variables __doc__ , our own variables are generally not used this variable name;

_xxx __xxx a function or variable like this is nonpublic (private) and should not be directly referenced, such as _abc , __abc etc.

The reason why we say that private functions and variables should not be directly referenced, rather than "cannot" be directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, but from a programming habit should not refer to private functions or variables.

Install third-party libraries

Windows ensures that Python is installed with the check box pip andAdd python.exe to Path.

When you try to run under a command Prompt window pip , if the Windows prompt does not find a command, you can rerun Setup to add the program pip .

Note: The Python 3.x and Python 2.x may coexist on Mac or Linux, so the corresponding PIP command ispip3

Now, let's install a third-party library,--python Imaging Library, which is a very powerful tool library for processing images under Python. However, PIL currently only supports Python 2.7 and has not been updated for years, so the PIL-based

Pillow project development is very active and supports the latest Python 3

Generally speaking Third-party libraries will be registered in the official Python pypi.python.org website, to install a third-party library, you must first know the name of the library, you can search on the official website or pypi, such as pillow name is called pillow, so the installation of Pillow command is:

Pip install Pillow, patiently waiting to download and install, you can use Pillow.

Module Search Path

When we try to load a module, Python searches for the corresponding. py file under the specified path, and if it doesn't, it will get an error.

By default, the Python interpreter searches the current directory, all installed built-in modules, and third-party modules, and the search path is stored in the sys variables of the module path :

If we want to add our own search directory, there are two ways:

One is to modify directly sys.path , add the directory to search:

This method is modified at run time and is invalidated after the run is finished.

The second method is to set the environment variable PYTHONPATH , and the contents of the environment variable are automatically added to the module search path. Settings are similar to setting the PATH environment variable. Note that you only need to add your own search path, and Python's own search path will not be affected.

Python Basics Dry 02

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.