python范例

Python is a general purpose programming language which is dynamically typed, interpreted, and known for its easy readability with great design principles.

Python是一种通用的编程语言,可以动态键入,解释并以其易于阅读的内容以及出色的设计原理而闻名。

freeCodeCamp has one of the most popular courses on Python. It's completely free (and doesn't even have any advertisements). You can watch it on YouTube here.

freeCodeCamp拥有Python上最受欢迎的课程之一。 它是完全免费的(甚至没有任何广告)。 您可以在YouTube上观看它 。

Python数据结构示例 (Python Data Structures Example)

Some general information about floating point numbers and how they work in Python, can be found here.

有关浮点数及其在Python中的工作方式的一些常规信息,请参见此处 。

Nearly all implementations of Python follow the IEEE 754 specification: Standard for Binary Floating-Point Arithmetic. More information found on the IEEE site.

Python的几乎所有实现都遵循IEEE 754规范:二进制浮点算术标准。 有关更多信息,请参见IEEE网站 。

Float objects can be created using floating point literals:

浮动对象可以使用浮点文字来创建:

>>> 3.14
3.14
>>> 314\.    # Trailing zero(s) not required.
314.0
>>> .314    # Leading zero(s) not required.
0.314
>>> 3e0
3.0
>>> 3E0     # 'e' or 'E' can be used.
3.0
>>> 3e1     # Positive value after e moves the decimal to the right.
30.0
>>> 3e-1    # Negative value after e moves the decimal to the left.
0.3
>>> 3.14e+2 # '+' not required but can be used for exponent part.
314.0

Numeric literals do not contain a sign, however creating negative float objects is possible by prefixing with a unary - (minus) operator with no space before the literal:

数字文字不包含一个标志,但是带来负面浮动对象可以通过用一元前缀-减号)运算符与前字面没有空间:

>>> -3.141592653589793
-3.141592653589793
>>> type(-3.141592653589793)
<class 'float'>

Likewise, positive float objects can be prefixed with a unary + (plus) operator with no space before the literal. Usually + is omitted:

同样,正浮点对象可以在文字前加一元+ (加号)运算符作为前缀,且中间不能有空格。 通常+被省略:

>>> +3.141592653589793
3.141592653589793

Note that leading and trailing zero(s) are valid for floating point literals.

请注意,前导零和尾随零对浮点字面量有效。

Likewise, positive float objects can be prefixed with a unary + (plus) operator with no space before the literal. Usually + is omitted:

同样,正浮点对象可以在文字前加一元+ (加号)运算符作为前缀,且中间不能有空格。 通常+被省略:

>>> +3.141592653589793
3.141592653589793

Note that leading and trailing zero(s) are valid for floating point literals.

请注意,前导零和尾随零对浮点字面量有效。

>>> 0.0
0.0
>>> 00.00
0.0
>>> 00100.00100
100.001
>>> 001e0010      # Same as 1e10
10000000000.0

The float constructor is another way to create float objects.

float构造函数是创建float对象的另一种方法。

Creating float objects with floating point literals is preferred when possible:

如果可能,最好使用浮点文字创建float对象:

>>> a = 3.14         # Prefer floating point literal when possible.
>>> type(a)
<class 'float'>
>>> b = int(3.14)    # Works but unnecessary.
>>> type(b)
<class 'float'>

However, the float constructor allows for creating float objects from other number types:

但是,float构造函数允许从其他数字类型创建float对象:

>>> a = 4
>>> type(a)
<class 'int'>
>>> print(a)
4
>>> b = float(4)
>>> type(b)
<class 'float'>
>>> print(b)
4.0
>>> float(400000000000000000000000000000000)
4e+32
>>> float(.00000000000000000000000000000004)
4e-32
>>> float(True)
1.0
>>> float(False)
0.0

The float constructor will also make float objects from strings that represent number literals:

float构造函数还将根据表示数字文字的字符串制作float对象:

>>> float('1')
1.0
>>> float('.1')
0.1
>>> float('3.')
3.0
>>> float('1e-3')
0.001
>>> float('3.14')
3.14
>>> float('-.15e-2')
-0.0015

The float constructor can also be used to make numeric representations of NaN (Not a Number), negative infinity and infinity (note that strings for these are case insensitive):

float构造函数还可用于制作NaN (非数字),负infinityinfinity数字表示形式(请注意,这些字符串不区分大小写):

>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf

复数 (Complex Numbers)

Complex numbers have a real and an imaginary part, each represented by a floating point number.

复数具有实部和虚部,每一个均由浮点数表示。

The imaginary part of a complex number can be created using an imaginary literal, this results in a complex number with a real part of 0.0:

可以使用虚数文字来创建复数的虚数部分,这将导致实数部分为0.0的复数:

>>> a = 3.5j
>>> type(a)
<class 'complex'>
>>> print(a)
3.5j
>>> a.real
0.0
>>> a.imag
3.5

No literal exists for creating a complex number with non-zero real and imaginary parts. To create a non-zero real part complex number, add an imaginary literal to a floating point number:

不存在用于创建具有非零实部和虚部的复数的文字。 要创建非零实部复数,请将虚构文字添加到浮点数:

>>> a = 1.1 + 3.5j
>>> type(a)
<class 'complex'>
>>> print(a)
(1.1+3.5j)
>>> a.real
1.1
>>> a.imag
3.5

Or use the complex constructor.

或使用复杂的构造函数 。

class complex([real[, imag]])

The arguments used to call the complex constructor can be of numeric (including complex) type for either parameter:

用于调用复杂构造函数的参数对于任何一个参数都可以是数字(包括complex )类型的:

>>> complex(1, 1)
(1+1j)
>>> complex(1j, 1j)
(-1+1j)
>>> complex(1.1, 3.5)
(1.1+3.5j)
>>> complex(1.1)
(1.1+0j)
>>> complex(0, 3.5)
3.5j

A string can also be used as the argument. No second argument is allowed if a string is used as an argument

string也可以用作参数。 如果将字符串用作参数,则不允许第二个参数

>>> complex("1.1+3.5j")
(1.1+3.5j)

Python Bools示例 (Python Bools Example)

bool() is a built-in function in Python 3. This function returns a Boolean value, i.e. True or False. It takes one argument, x.

bool()是Python 3中的内置函数。此函数返回布尔值,即True或False。 它需要一个参数x

争论 (Arguments)

It takes one argument, x. x is converted using the standard Truth Testing Procedure.

它需要一个参数xx是使用标准真相测试程序转换的。

返回值 (Return Value)

If x is false or omitted, this returns False; otherwise it returns True.

如果x为false或省略,则返回False ; 否则返回True

代码样例 (Code Sample)

print(bool(4 > 2)) # Returns True as 4 is greater than 2
print(bool(4 < 2)) # Returns False as 4 is not less than 2
print(bool(4 == 4)) # Returns True as 4 is equal to 4
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds
print(bool(4)) # Returns True as 4 is a non-zero value
print(bool(-4)) # Returns True as -4 is a non-zero value
print(bool(0)) # Returns False as it is a zero value
print(bool('dskl')) # Returns True as the string is a non-zero value
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing

Python Bool运算子范例 (Python Bool Operators Example)

and, or, not

and ornot

Python Docs - Boolean Operations

Python Docs-布尔运算

These are the Boolean operations, ordered by ascending priority:

这些是布尔运算,按优先级升序排列:

OperationResultNotes x or y if x is false, then y, else x (1) x and y if x is false, then x, else y (2) not x if x is false, then True, else False (3).

OperationResultNotes如果x为False,则为x或y,否则为y,否则为x(1)x,如果x为False,则为x,否则为x(y),否则为y(2);如果x为false,则为y(2),否则为y(2)。

Notes:

笔记:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.这是一个短路运算符,因此只有第一个为False时,它才求值第二个参数。
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is True.这是一个短路运算符,因此只有第一个为True时,它才评估第二个参数。
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.not的优先级低于非布尔运算符,因此a == b不会被解释为not(a == b),而a == not b是语法错误。

例子: (Examples:)

not (not:)

>>> not True
False
>>> not False
True

and (and:)

>>> True and False    # Short-circuited at first argument.
False
>>> False and True    # Second argument is evaluated.
False
>>> True and True     # Second argument is evaluated.
True

or (or:)

>>> True or False    # Short-circuited at first argument.
True
>>> False or True    # Second argument is evaluated.
True
>>> False or False   # Second argument is evaluated.
False

Python常数范例 (Python Constant Example)

Three commonly used built-in constants:

三个常用的内置常量:

  • True: The true value of the bool type. Assignments to True raise a SyntaxError.

    True布尔类型的真实值。 分配给True引发SyntaxError

  • False: The false value of the bool type. Assignments to False raise a SyntaxError.

    False布尔类型的假值。 赋值为False引发SyntaxError

  • None : The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None raise a SyntaxError.

    None :类型NoneType的唯一值。 当没有将默认参数传递给函数时,通常不使用None来表示缺少值。 分配给None引发SyntaxError

Other built-in constants:

其他内置常量:

  • NotImplemented: Special value which should be returned by the binary special methods, such as __eg__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type.

    NotImplemented :特殊值,应由二进制特殊方法(例如__eg__()__add__() __eg__()__add__() __rsub__()等)返回,以指示未针对其他类型实现该操作。

  • Ellipsis: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.

    Ellipsis :特殊值,通常与用户定义的容器数据类型的扩展切片语法结合使用。

  • __debug__: True if Python was not started with an -o option.

    __debug__ :如果Python没有以-o选项启动, __debug__ true。

Constants added by the site module. The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.

站点模块添加的常量。 站点模块(在启动期间会自动导入,除非指定了-S命令行选项)会向内置名称空间添加多个常量。 它们对于交互式解释程序外壳很有用,不应在程序中使用。

Objects that, when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code:

对象,在打印时将打印诸如“使用quit()或Ctrl-D(即EOF)退出”之类的消息,并在调用时以指定的退出代码引发SystemExit:

  • quit(code=None)退出(代码=无)
  • exit(code=None)退出(代码=无)

Objects that, when printed, print a message like “Type license() to see the full license text”, and when called, display the corresponding text in a pager-like fashion (one screen at a time):

对象,这些对象在打印时将显示诸如“输入license()以查看完整的许可证文本”之类的消息,并在被调用时以类似寻呼机的方式显示相应的文本(一次显示一个屏幕):

  • copyright版权
  • license执照
  • credits学分

调用Python函数示例 (Calling Python Function Example)

A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).

函数定义语句不执行该函数。 执行(调用)函数是通过在函数名称后加上括号将必需的参数(如果有)括起来来完成的。

>>> def say_hello():
...     print('Hello')
...
>>> say_hello()
Hello

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table.

函数的执行引入了一个新的符号表,用于该函数的局部变量。 更准确地说,函数中的所有变量分配将值存储在本地符号表中。

On the other hand, variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

另一方面,变量引用首先在本地符号表中查找,然后在封闭函数的本地符号表中查找,然后在全局符号表中查找,最后在内置名称表中查找。 因此,尽管可以引用全局变量,但不能在函数内直接为其赋值(除非在全局语句中命名)。

>>> a = 1
>>> b = 10
>>> def fn():
...     print(a)    # local a is not assigned, no enclosing function, global a referenced.
...     b = 20      # local b is assigned in the local symbol table for the function.
...     print(b)    # local b is referenced.
...
>>> fn()
1
20
>>> b               # global b is not changed by the function call.
10

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called. In this way, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.

函数调用的实际参数(参数)在被调用时被引入到被调用函数的本地符号表中。 这样,就可以通过按值调用来传递参数(该值始终是对象引用,而不是对象的值)。 当一个函数调用另一个函数时,将为该调用创建一个新的本地符号表。

>>> def greet(s):
...     s = "Hello " + s    # s in local symbol table is reassigned.
...     print(s)
...
>>> person = "Bob"
>>> greet(person)
Hello Bob
>>> person                  # person used to call remains bound to original object, 'Bob'.
'Bob'

The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:

用于调用函数的参数不能由该函数重新分配,但是引用可变对象的参数可以更改其值:

>>> def fn(arg):
...     arg.append(1)
...
>>> a = [1, 2, 3]
>>> fn(a)
>>> a
[1, 2, 3, 1]

Python类示例 (Python Class Example)

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

类提供了一种将数据和功能捆绑在一起的方法。 创建新类将创建一种新的对象类型,从而允许创建该类型的新实例。 每个类实例可以具有附加的属性以维护其状态。 类实例还可以具有用于修改其状态的方法(由其类定义)。

Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++.

与其他编程语言相比,Python的类机制以最少的新语法和语义添加了类。 它是C ++中的类机制的混合体。

Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name.

Python类提供了面向对象编程的所有标准功能:类继承机制允许多个基类,派生类可以覆盖其一个或多个基类的任何方法,并且一个方法可以调用具有相同名称的基类的方法。

Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

对象可以包含任意数量和种类的数据。 就像模块一样,类具有Python的动态特性:它们在运行时创建,并且可以在创建后进行进一步修改。

类定义语法: (Class Definition Syntax :)

The simplest form of class definition looks like this:

类定义的最简单形式如下所示:

class ClassName:<statement-1>.........<statement-N>

类对象: (Class Objects:)

Class objects support two kinds of operations: attribute references and instantiation.

类对象支持两种操作:属性引用和实例化。

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

属性引用使用Python中所有属性引用使用的标准语法: obj.name 。 有效属性名称是创建类对象时在类名称空间中的所有名称。 因此,如果类定义如下所示:

class MyClass:""" A simple example class """i = 12345def f(self):return 'hello world'

Then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute, returning the docstring belonging to the class: "A simple example class".

然后MyClass.iMyClass.f是有效的属性引用,分别返回整数和函数对象。 也可以将类属性分配给它,因此您可以通过分配来更改MyClass.i的值。 __doc__也是有效的属性,它返回属于以下类的docstring: "A simple example class"

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):

类实例化使用函数表示法。 只是假装类对象是一个无参数函数,它将返回该类的新实例。 例如(假设上面的类):

x = MyClass()

Creates a new instance of the class and assigns this object to the local variable x.

创建该类的新实例,并将该对象分配给局部变量x。

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named init(), like this:

实例化操作(“调用”类对象)创建一个空对象。 许多类喜欢创建具有定制为特定初始状态的实例的对象。 因此,一个类可以定义一个名为init ()的特殊方法,如下所示:

def __init__(self):self.data = []

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:

当类定义__init__()方法时,类实例化将自动为新创建的类实例调用__init__() 。 因此,在此示例中,可以通过以下方式获取新的初始化实例:

x = MyClass()

Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,

当然, __init__()方法可以具有更大的灵活性。 在这种情况下,提供给类实例化运算符的参数将传递给__init__() 。 例如,

class Complex:def __init__(self, realpart, imagpart):self.r = realpartself.i = imagpart...x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

Python代码块和缩进示例 (Python Code Blocks and Indention Example)

It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a TabError, and your program will crash. Be consistent when you code - choose either to indent using tabs or spaces and follow your chosen convention throughout your program.

通常,对于您来说,在Python中进行编码时,不要混用制表符和空格是一种很好的做法。 这样做可能会导致TabError ,并且您的程序将崩溃。 编码时保持一致-选择使用制表符或空格进行缩进,并在整个程序中遵循所选的约定。

代码块和缩进 (Code Blocks and Indentation)

One of the most distinctive features of Python is its use of indentation to mark blocks of code. Consider the if-statement from our simple password-checking program:

Python最独特的功能之一是它使用缩进来标记代码块。 考虑一下我们简单的密码检查程序中的if语句:

if pwd == 'apple':print('Logging on ...')
else:print('Incorrect password.')print('All done!')

The lines print(‘Logging on …’) and print(‘Incorrect password.’) are two separate code blocks. These happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.

行print('Logging on ...')和print('Incorrect password。')是两个单独的代码块。 它们恰好只有一行,但是Python允许您编写由任意数量的语句组成的代码块。

To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.

要在Python中指示代码块,您必须使代码块的每一行缩进相同的数量。 我们的示例if语句中的两个代码块都缩进了四个空格,这是Python的典型缩进量。

In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print(‘All done!’) is not indented, and so is not part of the else-block.

在大多数其他编程语言中,缩进仅用于帮助使代码看起来更漂亮。 但是在Python中,需要指出语句属于哪个代码块。 例如,最终打印(“ All done!”)没有缩进,因此也不是else块的一部分。

Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.

熟悉其他语言的程序员经常会想到缩进很重要:许多程序员喜欢自由地格式化自己喜欢的代码。 但是,Python缩进规则非常简单,大多数程序员已经使用缩进使代码可读。 Python只是将这一想法更进一步,并为缩进赋予了意义。

如果/省略语句 (If/elif-statements)

An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following “child” ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:

if / elif语句是具有多个条件的广义if语句。 它用于做出复杂的决定。 例如,假设一家航空公司具有以下“儿童”机票价格:2岁或以下的儿童免费乘坐飞机,2岁以上但13岁以下的儿童可享受折扣儿童票价,而13岁以上的任何人均可享受常规成人票价。 以下程序确定乘客应支付的费用:

# airfare.py
age = int(input('How old are you? '))
if age <= 2:print(' free')
elif 2 < age < 13:print(' child fare)
else:print('adult fare')

After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given.

Python从用户处获得年龄后,它将进入if / elif语句,并按照给出的顺序依次检查每个条件。

So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.

因此,首先检查年龄是否小于2,如果小于2,则表明飞行是自由的,并跳出了省略条件。 如果age不小于2,则它检查下一个elif条件,以查看age是否在2到13之间。如果是,则打印适当的消息并跳出if / elif语句。 如果if条件和elif条件都不为True,则它将在else块中执行代码。

条件表达式 (Conditional expressions)

Python has one more logical operator that some programmers like (and some don’t!). It’s essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:

Python还有一个逻辑运算符,有些程序员喜欢(有些则不喜欢!)。 它本质上是if语句的简写形式,可以在表达式中直接使用。 考虑以下代码:

food = input("What's your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'

The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either ‘yuck’ or ‘yum’. It’s equivalent to the following:

第二行中=右侧的表达式称为条件表达式,其结果为'yuck'或'yum'。 等效于以下内容:

food = input("What's your favorite food? ")
if food == 'lamb':reply = 'yuck'
else:reply = 'yum'

Conditional expressions are usually shorter than the corresponding if/else-statements, although not quite as flexible or easy to read. In general, you should use them when they make your code simpler.

条件表达式通常比相应的if / else语句短,尽管不够灵活或不易阅读。 通常,当它们使您的代码更简单时,应使用它们。

Python比较运算符示例 (Python Comparison Operator Example)

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Python中有八种比较操作。 它们都具有相同的优先级(高于布尔运算的优先级)。 比较可以任意链接; 例如, x < y <= z等效于x < y and y <= z ,除了y仅被评估一次(但是在两种情况下,当x < y被发现为假时, z都不被评估)。

The following summarizes the comparison operations:

以下总结了比较操作:

Operation Meaning
< strictly less than
<= less than or equal to
> strictly greater than
>= greater than or equal to
== equal to
!= not equal to
is object identity
is not negated object identity
运作方式 含义
< 严格小于
<= 小于或等于
> 严格大于
>= 大于或等于
== 等于
!= 不等于
is 对象身份
is not 否定对象身份

Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.

除不同的数字类型外,不同类型的对象永远不会比较相等。 此外,某些类型(例如,功能对象)仅支持退化的比较概念,其中该类型的任何两个对象都不相等。 当将复数与另一种内置数字类型进行比较,对象具有无法比较的不同类型或在其他情况下未定义时, <<=>>=运算符将引发TypeError异常。订购。

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__()method.

通常,除非类定义__eq__()方法,否则类的不同实例通常比较为不相等。

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__(), __le__(), __gt__(), and __ge__() (in general, __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators).

一个类的实例不能相对于同一类的其他实例或其他类型的对象进行排序,除非该类定义了足够的方法__lt__()__le__() __lt__()__le__() __gt__()__ge__() (通常) , __lt__()__eq__()就足够了,如果您需要比较运算符的常规含义)。

The behavior of the is and is not operators cannot be customized; also they can be applied to any two objects and never raise an exception.

isis not运算符的行为无法自定义; 它们也可以应用于任何两个对象,并且永远不会引发异常。

We can also chain < and > operators together. For instance, 3 < 4 < 5 will return True, but 3 < 4 > 5will not. We can also chain the equality operator. For instance, 3 == 3 < 5 will return True but 3 == 5 < 5 will not.

我们还可以将<>运算符链接在一起。 例如, 3 < 4 < 5将返回True ,而3 < 4 > 5将不返回True 。 我们还可以链接相等运算符。 例如, 3 == 3 < 5将返回True3 == 5 < 5将不返回True

平等比较-“是”与“ ==” (Equality Comparisons - “is” vs ”==”)

In Python, there are two comparison operators which allow us to check to see if two objects are equal. The is operator and the == operator. However, there is a key difference between them!

在Python中,有两个比较运算符可让我们检查两个对象是否相等。 is运算符和==运算符。 但是,它们之间有一个关键的区别!

The key difference between ‘is’ and ’==’ can be summed up as:

“ is”和“ ==”之间的关键区别可以总结为:

  • is is used to compare identity

    is用来比较认同

  • == is used to compare equality

    ==用于比较相等

(Example)

First, create a list in Python.

首先,在Python中创建一个列表。

myListA = [1,2,3]

Next, create a copy of that list.

接下来,创建该列表的副本。

myListB = myListA

If we use the ’==’ operator or the ‘is’ operator, both will result in a True output.

如果我们使用'=='运算符或'is'运算符,则两者都会产生True输出。

>>> myListA == myListB # both lists contains similar elements
True
>>> myListB is myListA # myListB contains the same elements
True

This is because both myListA and myListB are pointing to the same list variable, which I defined at beginning of my Python program. Both lists are exactly the same, both in identity and in content.

这是因为myListA和myListB都指向相同的列表变量,该变量是我在Python程序开始时定义的。 这两个列表在身份和内容上都完全相同。

However, what if I now create a new list?

但是,如果我现在创建一个新列表怎么办?

myListC = [1,2,3]

Performing the == operator still shows that both lists are the same, in terms of content.

就内容而言,执行==运算符仍显示两个列表相同。

>>> myListA == myListC
True

However, performing the is operator will now produce a False output. This is because myListA and myListC are two different variables, despite containing the same data. Even though they look the same, they are different.

但是,执行is运算符现在将产生False输出。 这是因为myListA和myListC是两个不同的变量,尽管它们包含相同的数据。 即使它们看起来相同,也不同

>>> myListA is myListC
False # both lists have different reference

To sum up:

总结一下:

  • An is expression outputs True if both variables are pointing to the same reference

    如果两个变量都指向同一个引用,则一个is表达式输出True

  • An == expression outputs True if both variables contain the same data

    如果两个变量包含相同的数据,则==表达式将输出True

Python字典范例 (Python Dictionary Example)

A Dictionary (a.k.a “dict”) in python is a built-in datatype that can be used to store key-value pairs. This allows you to treat a dict like it’s a database to store and organize data.

python中的Dictionary(又称“ dict”)是一种内置数据类型,可用于存储key-value对。 这使您可以像处理数据库一样存储存储和组织数据的dict

The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for existence - which means that we can easily determine if a specific key is present in the dictionary without needing to examine every element. The Python interpreter can just go to the location key and check if the key is there.

字典的特殊之处在于它们的实现方式。 类似哈希表的结构使检查是否存在变得容易-这意味着我们可以轻松确定字典中是否存在特定键,而无需检查每个元素。 Python解释器可以仅转到位置键,然后检查该键是否在那里。

Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)

字典几乎可以使用任何任意数据类型(例如字符串,整数等)作为键。 但是,不可散列的值(即包含列表,字典或其他可变类型的值(按值而不是对象标识进行比较))不能用作键。 用于键的数字类型遵循数字比较的一般规则:如果两个数字比较相等(例如11.0 ),则可以互换使用它们来索引同一字典条目。 (但是请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)

One most important requirement of a dictionary is that the keys must be unique.

字典最重要的要求是键必须唯一。

To create an empty dictionary just use a pair of braces:

要创建一个空字典,只需使用一对大括号:

>>> teams = {}>>> type(teams)>>> <class 'dict'>

To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs:

要创建具有一些初始值的非空字典,请放置一个逗号分隔的键值对列表:

>>> teams = {'barcelona': 1875, 'chelsea': 1910}>>> teams{'barcelona': 1875, 'chelsea': 1910}

It’s easy to add key-value pairs to an existing dictionary:

将键值对添加到现有字典很容易:

>>> teams['santos'] = 1787>>> teams{'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !>>> # extracting value - Just provide the key...>>> teams['barcelona']1875

del operator is used to delete a key-value pair from the dict. In scenarios where a key that’s already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that it’s an error to extract the value using a non-existent key.

del运算符用于从dict中删除键值对。 在已经使用过的键再次用于存储值的情况下,与该键关联的旧值将完全丢失。 另外,请记住,使用不存在的键提取值是错误的。

>>> del teams['santos']>>> teams{'chelsea': 1910, 'barcelona': 1875}>>> teams['chelsea'] = 2017 # overwriting    >>> teams{'chelsea': 2017, 'barcelona': 1875}

in keyword can be used to check whether a key exist in the dict or not:

in关键字可用于检查字典中是否存在键:

>>> 'sanots' in teamsFalse    >>> 'barcelona' in teamsTrue>>> 'chelsea' not in teamsFalse

keys is a built-in method that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists:

keys是一种内置方法 ,可用于获取给定字典的键。 要将字典中存在的键提取为列表:

>>> club_names = list(teams.keys())    >>> club_names['chelsea', 'barcelona']

Yet another way of creating a dictionary is using the dict() method:

创建字典的另一种方法是使用dict()方法:

>>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed  >>> players{'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}>>> >>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments...>>> dict( totti = 38, zidane = 43 ){'zidane': 43, 'totti': 38}

Dict comprehensions can be used as well to create dictionaries from arbitrary key and value expressions:

字典理解也可以用于根据任意键和值表达式创建字典:

>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}

Looping in DictionaryTo simply loop over the keys in the dictionary, rather than the keys and values:

在字典中循环仅在字典中的键而不是键和值上循环:

>>> d = {'x': 1, 'y': 2, 'z': 3} >>> for key in d:...     print(key) # do something...xyz

To loop over both key and value, you can use the following:For Python 2.x:

要遍历键和值,可以使用以下命令:对于Python 2.x:

>>> for key, item in d.iteritems():...     print items...123

Use items() for Python 3.x:

对Python 3.x使用items()

>>> for key, item in d.items():...     print(key, items)...x 1y 2z 3

Python对象示例 (Python Objects Example)

In Python, everything is an object.

在Python中,一切都是对象

Objects represent a logical grouping of attributes. Attributes are data and/or functions. When an object is created in Python it is created with an identity, type, and value.

对象代表属性的逻辑分组。 属性是数据和/或功能。 用Python创建对象时,将使用标识类型创建对象。

In other languages, primitives are values that have no properties (attributes). For example, in javascript undefined, null, boolean, string, number, and symbol (new in ECMAScript 2015) are primitives.

在其他语言中, 原始数据是没有属性 (属性) 。 例如,在javascript undefinednullbooleanstringnumbersymbol (ECMAScript 2015中的新增功能)是基元。

In Python, there are no primitives. None, booleans, strings, numbers, and even functions are all objects regardless how they are created.

在Python中,没有原语。 None布尔值字符串数字甚至函数都是对象,无论它们如何创建。

We can demonstrate this using some built-in functions:

我们可以使用一些内置函数来演示这一点:

  • id

    id

  • type

    type

  • dir

    dir

  • issubclass

    issubclass

Built-in constants None, True, and False are objects:

内置常量NoneTrueFalse对象

We test the None object here.

我们在这里测试None对象。

>>> id(None)
4550218168
>>> type(None)
<class 'NoneType'>
>>> dir(None)
[__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> issubclass(type(None), object)
True

Next, let’s inspect True.

接下来,让我们检查True

>>> id(True)
4550117616
>>> type(True)
<class 'bool'>
>>> dir(True)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(True), object)
True

No reason to leave out False!

没有理由遗漏False

>>> id(False)
4550117584
>>> type(False)
<class 'bool'>
>>> dir(False)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(False), object)
True

Strings, even when created by a string literals, are also objects.

字符串 ,即使通过字符串文字创建的,也是对象

>>> id("Hello campers!")
4570186864
>>> type('Hello campers!')
<class 'str'>
>>> dir("Hello campers!")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> issubclass(type('Hello campers!'), object)
True

Same with numbers.

数字相同

>>> id(42)
4550495728
>>> type(42)
<class 'int'>
>>> dir(42)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(42), object)
True

函数也是对象 (Functions are Objects Too)

In Python, functions are first class objects.

在Python中,函数是一流的对象。

Functions in Python are also objects, created with an identity, type, and value. They too can be passed into other functions:

Python中的函数也是对象 ,使用标识类型值创建 。 它们也可以传递给其他功能

>>> id(dir)
4568035688
>>> type(dir)
<class 'builtin_function_or_method'>
>>> dir(dir)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> issubclass(type(dir), object)
True

It is also possible to bind functions to a name and call the bound function using that name:

也可以将函数绑定到名称,然后使用该名称调用绑定的函数:

>>> a = dir
>>> print(a)
<built-in function dir>
>>> a(a)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

名称绑定和别名功能 (Name Binding and Aliasing Functions)

When you define a function in Python, that function name is introduced into the current symbol table. The value of the function's name then has a type that's recognized as a user-defined function by the interpreter:

当您在Python中定义函数时,该函数名将引入当前的符号表中。 然后,函数名称的值具有一种类型,该类型被解释器识别为用户定义的函数:

>>> something = 1
>>> type(something)
<type 'int'>>>> def something():
...     pass
...
>>> type(something)
<type 'function'>>>> something = []
>>> type(something)
<type 'list'>

The value of the function can then be assigned to another name. After it's been reassigned, it can still be used as a function. Use this method to rename your functions:

然后可以将函数的值分配给另一个名称。 重新分配后,它仍然可以用作函数。 使用此方法来重命名您的函数:

>>> def something(n):
...     print(n)
...
>>> type(something)
<type 'function'>>>> s = something
>>> s(100)
100

Python元组 (Python Tuples)

A tuple is a sequence of Python objects. Tuples are immutable which means they cannot be modified after creation, unlike lists.

元组是一系列Python对象。 元组是不可变的,这意味着它们不能像列表一样在创建后进行修改。

Creation:

创建:

An empty tuple is created using a pair of round brackets, ():

使用一对圆括号()创建一个空tuple

>>> empty_tuple = ()>>> print(empty_tuple)()>>> type(empty_tuple)<class 'tuple'>>>> len(empty_tuple)0

A tuple with elements is created by separating the elements with commas (surrounding round brackets, (), are optional with exceptions):

通过用逗号分隔元素来创建带有元素的tuple (圆括号() ,是可选的):

>>> tuple_1 = 1, 2, 3       # Create tuple without round brackets.>>> print(tuple_1)(1, 2, 3)>>> type(tuple_1)<class 'tuple'>>>> len(tuple_1)3>>> tuple_2 = (1, 2, 3)     # Create tuple with round brackets.>>> print(tuple_2)(1, 2, 3)>>> tuple_3 = 1, 2, 3,      # Trailing comma is optional.>>> print(tuple_3)(1, 2, 3)>>> tuple_4 = (1, 2, 3,)    # Trailing comma in round brackets is also optional.>>> print(tuple_4)(1, 2, 3)

A tuple with a single element must have the trailing comma (with or without round brackets):

具有单个元素的tuple必须带有结尾逗号(带或不带圆括号):

>>> not_tuple = (2)    # No trailing comma makes this not a tuple.
>>> print(not_tuple)
2
>>> type(not_tuple)
<class 'int'>
>>> a_tuple = (2,)     # Single element tuple. Requires trailing comma.
>>> print(a_tuple)
(2,)
>>> type(a_tuple)
<class 'tuple'>
>>> len(a_tuple)
1
>>> also_tuple = 2,    # Round brackets omitted. Requires trailing comma.
>>> print(also_tuple)
(2,)
>>> type(also_tuple)
<class 'tuple'>

Round brackets are required in cases of ambiguity (if the tuple is part of a larger expression):

如果模棱两可,则需要使用方括号(如果元组是较大表达式的一部分):

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.

请注意,实际上是组成元组的逗号,而不是括号。 括号是可选的,除了在空元组的情况下,或者在需要它们以避免语法歧义的情况下。

For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

例如, f(a, b, c)是带有三个参数的函数调用,而f((a, b, c))是带有3个元组作为唯一参数的函数调用。

>>> print(1,2,3,4,)          # Calls print with 4 arguments: 1, 2, 3, and 41 2 3 4>>> print((1,2,3,4,))        # Calls print with 1 argument: (1, 2, 3, 4,)(1, 2, 3, 4)>>> 1, 2, 3 == (1, 2, 3)     # Equivalent to 1, 2, (3 == (1, 2, 3))(1, 2, False)>>> (1, 2, 3) == (1, 2, 3)   # Use surrounding round brackets when ambiguous.True

A tuple can also be created with the tuple constructor:

一个tuple也可以与创建的tuple的构造函数:

>>> empty_tuple = tuple()>>> print(empty_tuple)()>>> tuple_from_list = tuple([1,2,3,4])>>> print(tuple_from_list)(1, 2, 3, 4)>>> tuple_from_string = tuple("Hello campers!")>>> print(tuple_from_string)('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')>>> a_tuple = 1, 2, 3>>> b_tuple = tuple(a_tuple)    # If the constructor is called with a tuple forthe iterable,>>> a_tuple is b_tuple          # the tuple argument is returned.True

Accessing elements of a tuple:

访问tuple元素:

Elements of tuples are accessed and indexed the same way that lists are.

tuples元素的访问和索引编制方式与lists相同。

>>> my_tuple = 1, 2, 9, 16, 25
>>> print(my_tuple)
(1, 2, 9, 16, 25)

Zero indexed

零索引

>>> my_tuple[0]1>>> my_tuple[1]2>>> my_tuple[2]9

Wrap around indexing

环绕索引

>>> my_tuple[-1]25>>> my_tuple[-2]16

Packing and Unpacking:

包装与拆箱:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321and 'hello!' are packed together in a tuple. The reverse operation is also possible:

语句t = 12345, 54321, 'hello!' 是元组封装的一个例子:值1234554321'hello!' 被打包成一个元组。 反向操作也是可能的:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

这被适当地称为序列解压缩,适用于右侧的任何序列。 序列解压缩要求等号左侧的变量与序列中的元素一样多。 注意,多重分配实际上只是元组打包和序列拆包的组合。

>>> t = 1, 2, 3    # Tuple packing.>>> print(t)(1, 2, 3)>>> a, b, c = t    # Sequence unpacking.>>> print(a)1>>> print(b)2>>> print(c)3>>> d, e, f = 4, 5, 6    # Multiple assignment combines packing and unpacking.>>> print(d)4>>> print(e)5>>> print(f)6>>> a, b = 1, 2, 3       # Multiple assignment requires each variable (right)have a matching element (left).Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: too many values to unpack (expected 2)

Immutable:

不变的:

tuples are immutable containers, guaranteeing which objects they contain will not change. It does not guarantee that the objects they contain will not change:

tuples是不可变的容器,保证它们含有不会改变对象。 它并不能保证它们含有不会改变的对象:

>>> a_list = []>>> a_tuple = (a_list,)    # A tuple (immutable) with a list (mutable) element.>>> print(a_tuple)([],)>>> a_list.append("Hello campers!")>>> print(a_tuple)         # Element of the immutable is mutated.(['Hello campers!'],)

Uses:

用途:

Functions can only return a single value, however, a heterogenuous tuple can be used to return multiple values from a function. One example is the built-in enumerate function that returns an iterable of heterogeneous tuples:

函数只能返回单个值,但是,异类tuple可以用于从函数返回多个值。 一个示例是内置的enumerate函数,该函数返回可迭代的异构tuples

>>> greeting = ["Hello", "campers!"]>>> enumerator = enumerate(greeting)>>> enumerator.next()>>> enumerator.__next__()(0, 'Hello')>>> enumerator.__next__()(1, 'campers!')

Python For循环语句示例 (Python For Loop Statement Example)

Python utilizes a for loop to iterate over a list of elements. This is unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.

Python利用for循环来遍历元素列表。 这与C或Java不同,后者使用for循环逐步更改值并使用该值访问数组等内容。

For loops iterate over collection-based data structures like lists, tuples, and dictionaries.

For循环遍历基于集合的数据结构,如列表,元组和字典。

The basic syntax is:

基本语法为:

for value in list_of_values:# use value inside this block

In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:

通常,您可以使用任何东西作为迭代器值,可以将可迭代项的条目分配到该值。 例如,您可以从元组列表中解包元组:

list_of_tuples = [(1,2), (3,4)]for a, b in list_of_tuples:print("a:", a, "b:", b)

On the other hand, you can loop over anything that is iterable. You can call a function or use a list literal.

另一方面,您可以遍历任何可迭代的对象。 您可以调用函数或使用列表文字。

for person in load_persons():print("The name is:", person.name)
for character in ["P", "y", "t", "h", "o", "n"]:print("Give me a '{}'!".format(character))

Some ways in which For loops are used:

使用For循环的一些方法:

Iterate over the range() function

遍历range()函数

for i in range(10):print(i)

Rather than being a function, range is actually an immutable sequence type. The output will contain results from lower bound i.e 0 to the upper bound i.e 10, but excluding 10. By default the lower bound or the starting index is set to zero. Output:

范围不是函数,实际上是不可变的序列类型。 输出将包含从下限即0到上限即10的结果,但不包括10。默认情况下,下限或起始索引设置为零。 输出:

>
0
1
2
3
4
5
6
7
8
9
>

Additionally, one can specify the lower bound of the sequence and even the step of the sequence by adding a second and a third parameter.

另外,可以通过添加第二个和第三个参数来指定序列的下限甚至序列的步骤。

for i in range(4,10,2): #From 4 to 9 using a step of twoprint(i)

Output:

输出:

>
4
6
8
>

xrange() function

xrange()函数

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.

在大多数情况下,xrange和range在功能方面完全相同。 它们都提供了一种生成整数列表供您使用的方法,但是您可以随意使用。 唯一的区别是range返回一个Python列表对象,而xrange返回一个xrange对象。 这意味着xrange在运行时实际上不会像range那样生成静态列表。 它使用称为yield的特殊技术根据需要创建值。 该技术与一种称为生成器的对象一起使用。

One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x

再增加一件事。 在Python 3.x中,不再存在xrange函数。 现在,范围函数可以执行xrange在Python 2.x中的功能

Iterate over values in a list or tuple

遍历列表或元组中的值

A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:print(value)

Output:

输出:

>
hello
1
65
thank you
[2, 3]
>

Iterate over keys in a dictionary (aka hashmap)

遍历字典中的键(也称为哈希图)

fruits_to_colors = {"apple": "#ff0000","lemon": "#ffff00","orange": "#ffa500"}for key in fruits_to_colors:print(key, fruits_to_colors[key])

Output:

输出:

>
apple #ff0000
lemon #ffff00
orange #ffa500
>

Iterate over two lists of same size in a single loop with the zip() function

使用zip()函数在一个循环中遍历两个相同大小的列表

A = ["a", "b", "c"]
B = ["a", "d", "e"]for a, b in zip(A, B):print a, b, a == b

Output:

输出:

>
a a True
b d False
c e False
>

Iterate over a list and get the corresponding index with the enumerate() function

遍历列表并使用enumerate()函数获取相应的索引

A = ["this", "is", "something", "fun"]for index,word in enumerate(A):print(index, word)

Output:

输出:

>
0 this
1 is
2 something
3 fun
>

A common use case is iterating over a dictionary:

一个常见的用例是遍历字典:

for name, phonenumber in contacts.items():print(name, "is reachable under", phonenumber)

If you absolutely need to access the current index of your iteration, do NOT use range(len(iterable))! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function enumerate() instead:

如果您绝对需要访问迭代的当前索引,请不要使用range(len(iterable)) ! 这是非常糟糕的做法,会让您从高级Python开发人员那里获得很多笑声。 使用内置函数enumerate()代替:

for index, item in enumerate(shopping_basket):print("Item", index, "is a", item)

for/else statements Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of break statement so that we can break out of the loop on a satisfied condition. If we do not break out then the else part will be executed.

for / else语句 Pyhton允许您将else与for循环一起使用,当不满足loop主体中with的条件时,将执行else情况。 要使用else,我们必须使用break语句,以便我们可以在满足条件的情况下跳出循环。 如果我们不休息,那么其他部分将被执行。

week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
today = 'Saturday'
for day in week_days:if day == today:print('today is a week day')break
else:print('today is not a week day')

In the above case the output will be today is not a week day since the break within the loop will never be executed.

在上述情况下,输出将today is not a week day因为循环内的中断将永远不会执行。

Iterate over a list using inline loop function

使用内联循环功能遍历列表

We could also iterate inline using python. For example if we need to uppercase all the words in a list from a list, we could simply do the following:

我们还可以使用python迭代内联。 例如,如果我们需要将列表中列表中的所有单词都大写,则可以简单地执行以下操作:

A = ["this", "is", "awesome", "shinning", "star"]UPPERCASE = [word.upper() for word in A]
print (UPPERCASE)

Output:

输出:

>
['THIS', 'IS', 'AWESOME', 'SHINNING', 'STAR']

Python函数范例 (Python Function Example)

A function allows you to define a reusable block of code that can be executed many times within your program.

函数允许您定义一个可重用的代码块,该代码块可以在程序中多次执行。

Functions allow you to create more modular and DRY solutions to complex problems.

通过函数,您可以为复杂问题创建更多的模块化和DRY解决方案。

While Python already provides many built-in functions such as print() and len(), you can also define your own functions to use within your projects.

尽管Python已经提供了许多内置函数,例如print()len() ,但您也可以定义自己的函数以在项目中使用。

One of the great advantages of using functions in your code is that it reduces the overall number of lines of code in your project.

在代码中使用函数的最大优点之一是,它减少了项目中代码的总行数。

句法 (Syntax)

In Python, a function definition has the following features:

在Python中,函数定义具有以下功能:

  1. The keyword def

    关键字def

  2. a function name函数名称
  3. parentheses’()’, and within parentheses input parameters, although the input parameters are optional.括号“()”和括号内的输入参数,尽管输入参数是可选的。
  4. a colon ’:’冒号':'
  5. some block of code to execute一些要执行的代码块
  6. a return statement (optional)返回语句(可选)
# a function with no parameters or returned values
def sayHello():print("Hello!")sayHello()  # calls the function, 'Hello!' is printed to the console# a function with a parameter
def helloWithName(name):print("Hello " + name + "!")helloWithName("Ada")  # calls the function, 'Hello Ada!' is printed to the console# a function with multiple parameters with a return statement
def multiply(val1, val2):return val1 * val2multiply(3, 5)  # prints 15 to the console

Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code more readable, easier to debug, and limits typing errors.

函数是可以简单地通过调用函数重用的代码块。 这样就可以简单,优雅地重用代码,而无需显式重写代码部分。 这使代码更具可读性,更易于调试,并限制了键入错误。

Functions in Python are created using the def keyword, followed by a function name and function parameters inside parentheses.

Python中的函数是使用def关键字创建的,其后是括号内的函数名称和函数参数。

A function always returns a value. The return keyword is used by the function to return a value. If you don’t want to return any value, the default value None will be returned.

函数总是返回一个值。 函数使用return关键字返回值。 如果您不想返回任何值,则将返回默认值None

The function name is used to call the function, passing the needed parameters inside parentheses.

函数名称用于调用函数,并在括号内传递所需的参数。

# this is a basic sum function
def sum(a, b):return a + bresult = sum(1, 2)
# result = 3

You can define default values for the parameters, and that way Python will interpret that the value of that parameter is the default one if none is given.

您可以为参数定义默认值,这样,如果没有给出参数,Python将解释为该参数的值是默认值。

def sum(a, b=3):return a + bresult = sum(1)
# result = 4

You can pass the parameters in the order you want, using the name of the parameter.

您可以使用参数名称以所需顺序传递参数。

result = sum(b=2, a=2)
# result = 4

However, it is not possible to pass a keyword argument before a non-keyword one.

但是,不可能在非关键字之前传递关键字参数。

result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError

Functions are also Objects, so you can assign them to a variable, and use that variable like a function.

函数也是对象,因此您可以将它们分配给变量,并像函数一样使用该变量。

s = sum
result = s(1, 2)
# result = 3

笔记 (Notes)

If a function definition includes parameters, you must provide the same number of parameters when you call the function.

如果函数定义包含参数,则在调用函数时必须提供相同数量的参数。

print(multiply(3))  # TypeError: multiply() takes exactly 2 arguments (0 given)print(multiply('a', 5))  # 'aaaaa' printed to the consoleprint(multiply('a', 'b'))  # TypeError: Python can't multiply two strings

The block of code that the function will run includes all statements indented within the function.

该函数将运行的代码块包括该函数内缩进的所有语句。

def myFunc():
print('this will print')
print('so will this')x = 7
# the assignment of x is not a part of the function since it is not indented

Variables defined within a function only exist within the scope of that function.

在函数中定义的变量仅存在于该函数的范围内。

def double(num):
x = num * 2
return xprint(x)  # error - x is not defined
print(double(4))  # prints 8

Python interprets the function block only when the function is called and not when the function is defined. So even if the function definition block contains some sort of error, the python interpreter will point that out only when the function is called.

Python仅在调用函数时解释功能块,而在定义函数时不解释。 因此,即使函数定义块包含某种错误,python解释器也只会在调用函数时指出这一点。

Python生成器示例 (Python Generator Example)

Generators are a special type of function that allows you to return values without ending a function. It does this by using the yield keyword. Similar to return, the yield expression will return a value to the caller. The key difference between the two is that yield will suspend the function, allowing for more values to be returned in the future.

生成器是一种特殊的函数类型,它使您可以在不结束函数的情况下返回值。 它通过使用yield关键字来做到这一点。 与return相似, yield表达式将向调用者返回一个值。 两者之间的主要区别是yield将暂停函数,从而允许将来返回更多值。

Generators are iterable so they can be used cleanly with for loops or anything else that iterates.

生成器是可迭代的,因此它们可以与for循环或其他任何可迭代使用的对象一起使用。

def my_generator():yield 'hello'yield 'world'yield '!'for item in my_generator():print(item)# output:
# hello
# world
# !

Like other iterators, generators can be passed to the next function to retrieve the next item. When a generator has no more values to yield, a StopIteration error is raised.

像其他迭代器一样,可以将生成器传递给next函数以检索下一个项目。 当生成器没有更多值可产生时,将引发StopIteration错误。

g = my_generator()
print(next(g))
# 'hello'
print(next(g))
# 'world'
print(next(g))
# '!'
print(next(g))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# StopIteration

Generators are particularly useful when you need to create a large set of values but do not need to keep them all in memory at the same time. For example, if you need to print the first million fibonacci numbers, you would typically return a list of a million values and iterate over the list to print each value. However with a generator, you can return each value one at a time:

当您需要创建大量值但不需要同时将它们全部保存在内存中时,生成器特别有用。 例如,如果您需要打印前一百万个斐波那契数字,则通常会返回一百万个值的列表,然后遍历该列表以打印每个值。 但是,对于生成器,您可以一次返回每个值:

def fib(n):a = 1b = 1for i in range(n):yield aa, b = b, a + bfor x in fib(1000000):print(x)

Python迭代器示例 (Python Iterator Example)

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.

Python支持在容器上进行迭代的概念。 这是通过两种不同的方法实现的: 这些用于允许用户定义的类支持迭代。

Python Docs - Iterator Types

Python Docs-迭代器类型

Iteration is the process of programmatically repeating a step a given number of times. A programmer can make use of iteration to perform the same operation on every item in a collection of data, for example printing out every item in a list.

迭代是通过编程将步骤重复给定次数的过程。 程序员可以利用迭代对数据集合中的每个项目执行相同的操作,例如打印列表中的每个项目。

  • Objects can implement a __iter__() method that returns an iterator object to support iteration.

    对象可以实现__iter__()方法,该方法返回迭代器对象以支持迭代。

Iterator objects must implement:

迭代器对象必须实现:

  • __iter__(): returns the iterator object.

    __iter__() :返回迭代器对象。

  • __next__(): returns the next object of the container.iteratorobject = ‘abc’.iter() print(iteratorobject) print(id(iteratorobject)) print(id(iteratorobject.iter())) # Returns the iterator itself. print(iteratorobject.next()) # Returns 1st object and advances iterator. print(iteratorobject.next()) # Returns 2nd object and advances iterator. print(iteratorobject.next()) # Returns 3rd object and advances iterator. print(iteratorobject.next()) # Raises StopIteration Exception.

    __next__() :返回容器的下一个对象__next__() 对象='abc'。 iter ()print(iterator对象)print(id(iterator 对象))print(id(iterator对象。iter ()))#返回迭代器本身。 打印(迭代器对象。 下一个 ())#返回第一对象和预付款迭代器。 打印(迭代器对象。 下一个 ())#返回第二对象和预付款迭代器。 打印(迭代器对象。 下一个 ())#返回第三对象和预付款迭代器。 打印(迭代器对象。 下一个 ())#引发StopIteration异常。

Output :

输出:

<str_iterator object at 0x102e196a0>
4343305888
4343305888
a
b
c
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-1-d466eea8c1b0> in <module>()6 print(iterator_object.__next__())     # Returns 2nd object and advances iterator.7 print(iterator_object.__next__())     # Returns 3rd object and advances iterator.
----> 8 print(iterator_object.__next__())     # Raises StopIteration Exception.StopIteration:

Python示例中的三元运算符 (Ternary operator in Python Example)

Ternary operations in Python, often also referred to as conditional expressions, allow the programmer to perform an evaluation and return a value based on the truth of the given condition.

Python中的三元操作(通常也称为条件表达式)允许程序员执行评估并根据给定条件的真值返回值。

The ternary operator differs from a standard if, else, elif structure in the sense that it is not a control flow structure, and behaves more like other operators such as == or != in the Python language.

三元运算符不同于标准ifelseelif结构,因为它不是控制流结构,并且其行为更像其他运算符,例如Python语言中的==!=

(Example)

In this example, the string Even is returned if the val variable is even, otherwise the string Odd is returned. The returned string is then assigned to the is_even variable and printed to the console.

在此示例中,如果val变量为偶数,则返回字符串Even ,否则返回字符串Odd 。 然后,将返回的字符串分配给is_even变量并打印到控制台。

输入值 (Input)

for val in range(1, 11):is_even = "Even" if val % 2 == 0 else "Odd"print(val, is_even, sep=' = ')

输出量 (Output)

1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even

Python While循环语句示例 (Python While Loop Statement Example)

Python utilizes the while loop similarly to other popular languages. The while loop evaluates a condition then executes a block of code if the condition is true. The block of code executes repeatedly until the condition becomes false.

Python与其他流行语言类似地利用while循环。 while循环评估条件,然后在条件为真时执行代码块。 代码块将重复执行,直到条件变为假。

The basic syntax is:

基本语法为:

counter = 0
while counter < 10:# Execute the block of code here as# long as counter is less than 10

An example is shown below:

一个例子如下所示:

days = 0
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
while days < 7:print("Today is " + week[days])days += 1

Output:

输出:

Today is Monday
Today is Tuesday
Today is Wednesday
Today is Thursday
Today is Friday
Today is Saturday
Today is Sunday

Line-by-Line explanation of the above CODE:

以上代码的逐行说明:

  1. the variable ‘days’ is set to a value 0.变量“天”设置为值0。
  2. a variable week is assigned to a list containing all the days of the week.将可变周分配给包含一周中所有日期的列表。
  3. while loop startswhile循环开始
  4. the block of code will be executed until the condition returns ‘true’.该代码块将一直执行,直到条件返回“ true”为止。
  5. the condition is ‘days<7’ which roughly says run the while loop until the point the variable days is less than 7条件是“ days <7”,大致表示运行while循环,直到变量days小于7
  6. So when the days=7 the while loop stops executing.因此,当days = 7时,while循环将停止执行。
  7. the days variable gets updated on every iteration.days变量在每次迭代中都会更新。
  8. When the while loop runs for the first time, the line ‘Today is Monday’ is printed onto the console and the variable days becomes equal to 1.当while循环第一次运行时,“今天是星期一”行被打印到控制台上,并且可变天数等于1。
  9. Since the variable days is equal to 1 which is less than 7,  the while loop is executed again.由于变量days等于1,小于7,因此将再次执行while循环。
  10. It goes on again and again and when the console prints ‘Today is Sunday’ the variable days is now equal to 7 and the while loop stops executing.它一遍又一遍地运行,并且当控制台显示“ Today is Sunday”时,变量天现在等于7,而while循环停止执行。

Python中的f字符串 (f-strings in Python)

In Python version 3.6, a new method of formatting strings was implemented. The new method is called Literal string interpolation (though commonly referred to as an f-string).

在Python 3.6版中,实现了一种格式化字符串的新方法。 新方法称为文字字符串插值(尽管通常称为f字符串)。

The use of f-string allows the programmer to dynamically insert a variable into a string in a clean and concise manner. In addition to inserting variables into a string this feature also also provides the ability for a programmer to evaluate expressions, join the contents of collection, and even invoke functions within the f-string.

f字符串的使用允许程序员以简洁明了的方式将变量动态地插入到字符串中。 除了将变量插入字符串外,此功能还为程序员提供了评估表达式,加入集合内容,甚至调用f字符串中的函数的功能。

To perform these dynamic behaviors within an f-string we wrap them inside curly brackets within the string, and prepend a lower case f to the beginning of the string (before the opening quote.

为了在f字符串中执行这些动态行为,我们将它们包装在字符串的大括号内,并在字符串的开头(在开始的引号之前)使用小写的f。

例子 (Examples)

Dynamically inserting a variable into a string at runtime:

在运行时动态地将变量插入字符串中:

name = 'Jon Snow'
greeting = f'Hello! {name}'
print(greeting)

Evaluate an expression in a string:

计算字符串中的表达式:

val1 = 2
val2 = 3
expr = f'The sum of {val1} + {val2} is {val1 + val2}'
print(expr)

Calling a function and inserting output within a string:

调用函数并在字符串中插入输出:

def sum(*args):result = 0for arg in args:result += argreturn resultfunc = f'The sum of 3 + 5 is {sum(3, 5)}'
print(func)

Joining the contents of a collection within a string:

在字符串中连接集合的内容:

fruits = ['Apple', 'Banana', 'Pear']list_str = f'List of fruits: {", ".join(fruits)}'
print(list_str)

如何安装Python 3 (How to Install Python 3)

You can download Python from this official link. Based on your OS (Windows or Linux or OSX), you might want to install Python 3 following these instructions.

您可以从此官方链接下载Python。 根据您的操作系统(Windows,Linux或OSX),您可能需要按照以下说明安装Python 3。

使用虚拟环境 (Using Virtual Environments)

It is always a great idea to sandbox your Python installation and keep it separate from your System Python. The System Python is the path to Python interpreter, which is used by other modules installed along with your OS.

沙盒化 Python安装并将其与System Python分开始终是一个好主意。 System Python是Python解释器的路径,与操作系统一起安装的其他模块也使用它。

It’s not safe to install Python Web-frameworks or libraries directly using System Python. Instead, you can use Virtualenv to create and spawn a separate Python process when you are developing Python applications.

直接使用System Python安装Python Web-frameworks或库是不安全的 。 相反,在开发Python应用程序时,可以使用Virtualenv创建和生成单独的Python进程。

虚拟包装器 (Virtualenvwrapper)

The Virtualenvwrapper module makes it easy for you to manage and sandbox multiple Python sandboxed environments in one machine, without corrupting any modules or services written in Python and used by your machine.

Virtualenvwrapper模块使您可以轻松地在一台计算机上管理和沙箱化多个Python沙箱环境,而不会破坏用Python编写并由计算机使用的任何模块或服务。

Of course, most cloud hosted development environments such as Nitrous or Cloud9 also come with these pre-installed and ready for you to get coding! You can quickly pick a box from your dashboard and start coding after activating a Python 3 environment.

当然,大多数云托管的开发环境(例如Nitrous或Cloud9)也都预先安装了这些,并准备好进行编码! 您可以从仪表板中快速选择一个框,并在激活Python 3环境后开始编码。

In Cloud9, you need to select the Django box while creating a new development environment.

在Cloud9中 ,您需要在创建新的开发环境时选择Django框。

A few shell command examples follow. If you wish to copy-paste, do note that the $ sign is a shorthand for the terminal prompt, it’s not part of the command. My terminal prompt looks something like this:

以下是一些shell命令示例。 如果要复制粘贴,请注意$符号是终端提示的简写,它不是命令的一部分。 我的终端提示符如下所示:

alayek:~/workspace (master) $

And, an ls would look like

而且, ls看起来像

alayek:~/workspace (master) $ ls

But, while writing the same in this documentation, I would be writing it as

但是,在本文档中编写相同内容的同时,我将其编写为

$ ls

Getting back to our discussion, you can create a Python 3 interpreter-included sandbox on Cloud9 by running on your cloud terminal:

回到我们的讨论,您可以通过在云终端上运行,在Cloud9上创建一个包含Python 3解释器的沙箱:

$ mkvirtualenv py3 --python=/usr/bin/python3

You have to run it only once after creating a new box for your project. Once executed, this command would create a new sandboxed virtualenv ready for you to use, named py3.

为项目创建新框后,只需运行一次。 一旦执行,此​​命令将创建一个新的沙盒py3 ,供您使用,名为py3

To view available virtual environments, you can use

要查看可用的虚拟环境,可以使用

$ workon

To activate py3, you can use the workon command with the name of the environment:

要激活py3 ,可以使用带有环境名称的workon命令:

$ workon py3

All three terminal commands above would also work on local Linux machines or OSX machines. These are virtualenvwrapper commands; so if you are planning on using them, make sure you have this module installed and added to PATH variable.

以上所有三个终端命令也将在本地Linux机器或OSX机器上工作。 这些是virtualenvwrapper命令; 因此,如果您打算使用它们,请确保已安装此模块并将其添加到PATH变量中。

If you are inside a virtual environment; you can easily find that out by checking your terminal prompt. The environment name will be clearly shown in your terminal prompt.

如果您在虚拟环境中; 您可以通过查看终端提示轻松找到这一点。 环境名称将在终端提示中清晰显示。

For instance, when I am inside the py3 environment, I will be seeing this as my terminal prompt:

例如,当我在py3环境中时,会在终端提示下看到以下内容:

(py3)alayek:~/workspace (master) $

Notice the (py3) in braces! If for some reason you are not seeing this, even if you are inside a virtual env; you can try doing one of the things mentioned here.

注意括号中的(py3) ! 如果由于某种原因您没有看到此消息,即使您位于虚拟环境中; 您可以尝试执行此处提到的其中一项操作。

To get out of a virtual environment or to deactivate one - use this command:

要退出虚拟环境或停用一个虚拟环境,请使用以下命令:

$ deactivate

Again, this works only with virtualenvwrapper module.

同样,这仅适用于virtualenvwrapper模块。

Pipenv (Pipenv)

An alternative to using virtualenvwrapper is Pipenv. It automatically creates virtual environments for your projects, and maintains a Pipfile which contains the dependencies. Using Pipenv means you no longer need to use pip and virtualenv separately, or manage your own requirements.txt file. For those familiar with JavaScript, Pipenv is similar to using a packaging tool like npm.

使用virtualenvwrapper的替代方法是Pipenv 。 它会自动为您的项目创建虚拟环境,并维护一个包含依赖项的Pipfile 。 使用Pipenv意味着您不再需要分别使用pip和virtualenv或管理自己的requirements.txt文件。 对于熟悉JavaScript的人来说,Pipenv类似于使用打包工具(如npm

To get started with Pipenv, you can follow this very detailed guide. Pipenv makes it easy to specify which version of Python you wish to use for each project, import from an existing requirements.txt file and graph your dependencies.

要开始使用Pipenv,您可以按照此非常详细的指南进行操作 。 Pipenv使您可以轻松地指定要用于每个项目的Python版本 ,从现有的requirements.txt文件导入并绘制依赖关系图 。

翻译自: https://www.freecodecamp.org/news/python-example/

python范例

python范例_最佳Python代码范例相关推荐

  1. 第一章 第一节:Python基础_认识Python

    Python基础入门(全套保姆级教程) 第一章 第一节:Python基础_认识Python 1. 什么是编程 通俗易懂,编程就是用代码编写程序,编写程序有很多种办法,像c语言,javaPython语言 ...

  2. html代码范例_最佳HTML范例和HTML5范例

    html代码范例 HTML provides the structure of websites. Here are some examples of how to use HTML syntax t ...

  3. 动态照片墙 python 实现_利用python生成照片墙的示例代码

    这篇文章主要介绍了利用python生成照片墙的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 PIL(Python Im ...

  4. python实验原理_【python】《统计学原理实验教程(Python)》书中代码实现

    代码已经上传至GitHub <统计学原理实验教程(Python)>书中代码实现 简介 <统计学原理实验教程(Python)>是厦门大学出版社在2019年出版的图书,主要通过py ...

  5. matlab代码用python替换_用python替换Matlab

    我是一名工程专业的学生,我必须做大量的数值处理,绘图,模拟等工作.我目前使用的工具是Matlab. 我在大学计算机上使用它来完成大部分任务. 但是,我想知道有哪些可用的免费选项. 我已经做过一些研究, ...

  6. java python算法_用Python,Java和C ++示例解释的排序算法

    java python算法 什么是排序算法? (What is a Sorting Algorithm?) Sorting algorithms are a set of instructions t ...

  7. python 3.7 最佳python中文工具书籍下载

    筛选了2年内优秀的python书籍,个别经典的书籍扩展到5年内. 筛选了2年内优秀的python书籍,个别经典的书籍扩展到5年内. python现在的主流版本是3.7(有明显性能提升,强烈推荐) 3. ...

  8. python 字符识别_使用python进行光学字符识别入门

    python 字符识别 语言模型设计 (Language Model Designing) Optical Character Recognition is the conversion of 2-D ...

  9. 复旦大学python培训_复旦大学Python之子高质量解读:Python400集视频教程+python电子书大合集...

    Python 简介: Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具 ...

最新文章

  1. Java技巧:用一个循环语句输出九九乘法表!
  2. Hive 导入CSV文件
  3. MySQL生产库开发规范
  4. VR:下一个技术风口
  5. 计算机丢失MSVCR71.dll处理方法
  6. 面试题汇总11-20
  7. Html给网页加icon图标
  8. 消失的2000万辆小黄车去哪儿了?
  9. eplan连接定义点不显示_EPLAN操作命令之线色设置
  10. 这俩 AI 项目贼有意思
  11. php 直接显示缩略图,PHP自动生成缩略图函数的源码示例
  12. 深入了解机器学习 (Descending into ML):线性回归
  13. Unix波澜壮阔的发展史
  14. tp无线监控显示服务器内部错误,无线监控摄像头连接Wi-Fi成功,但绑定TP-LINK ID失败?...
  15. 0-1背包问题和部分背包(fractional knapsack)问题分析
  16. Java 汉字转拼音 完整代码实例(包含多音字解决方案)
  17. windows操作系统的安装
  18. 短视频/直播+教育成为教育新常态
  19. 百度域名已备案,解析阿里服务器-出现未备案提示
  20. 从网易云音乐中总结banner设计

热门文章

  1. [小O地图-XOMAP] - 功能简介
  2. Mac - was compiled with optimization - stepping may behave oddly; variables may not be available.
  3. m4a怎么转换成mp3,m4a转mp3的简单方法
  4. ORACLE 金额转大写中文
  5. .Net Core微服务化ABP之六——处理Authentication
  6. 区块链技术的风险!(转载)
  7. iOS设计模式四部曲(二) 结构型模式 内附Demo
  8. 自动化测试工具 Selenium WebDriver 入门教程
  9. 专家警告全球芯片短缺可能持续到 2022 年之后
  10. JS ASCII码转换代码