Python Code Examples Python代码示例!

薛彭薄
2023-12-01

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

是一种通用编程语言,它具有很好的设计原则,因其易于阅读而动态地输入,解释和着名。

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

freeCodeCamp是Python上最受欢迎的课程之一。它是完全免费的(甚至没有任何广告)。您可以 watch it on YouTube here .

。Python资源共享群:626017123

 

 

 

 

 

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

可以找到有关浮点数以及它们如何在Python中工作的一些常规信息 here .

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

几乎所有Python的实现都遵循IEEE 754规范:二进制浮点运算标准。更多信息发现于 IEEE site.

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.

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

>>> 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.

对象。

Creating

创建 float objects with floating point literals is preferred when possible:

在可能的情况下,首选具有浮点文字的对象:

>>> 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('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')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf

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

是Python 3中的内置函数。此函数返回一个布尔值,即True或False。这需要一个论点, x .

Arguments{#arguments}

It takes one argument,

这需要一个论点, x .

。 x is converted using the standard

使用标准转换 Truth Testing Procedure .

Return Value{#return-value}

If

如果 x is false or omitted, this returns

是false或省略,返回 False ; otherwise it returns

;否则它会返回 True .

Code Sample{#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

and ,

, or ,

, not

Python Docs - Boolean Operations

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或y如果x为假,则为y,否则x(1)x和y如果x为假,则为x,否则y(2)不为x如果x为假,则为True,否则为False(3)。

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is 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.

Examples:{#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

Three commonly used built-in constants:

三种常用的内置常量:

  • True : The true value of the bool type. Assignments to True raise a SyntaxError .
  • False : The false value of the bool type. Assignments to False raise a 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 .

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.
  • Ellipsis : Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
  • __debug__ : True if Python was not started with an -o option.

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命令行选项)将向内置命名空间添加几个常量。它们对交互式解释器shell很有用,不应在程序中使用。

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:

打印时打印消息,如"使用退出()或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):

打印时打印"类型许可证()以查看完整许可证文本"的消息,并在调用时以类似寻呼机的方式显示相应的文本(一次一个屏幕):

  • copyright
  • license
  • credits

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.

调用函数调用的实际参数(参数)在被调用函数的本地符号表中引入。通过这种方式,使用call by value传递参数(其中值始终是对象引用,而不是对象的值)。当函数调用另一个函数时,将为该调用创建一个新的本地符号表。

>>> 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]

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 :{#class-definition-syntax-}

The simplest form of class definition looks like this:

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

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

Class Objects:{#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:

属性引用使用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:

。有效的属性名称是创建类对象时类的命名空间中的所有名称。所以,如果类定义看起来像这样:

class MyClass:
    """ A simple example class """
    i = 12345
    def 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:

也是一个有效的属性,返回属于该类的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:

(), 像这样:

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:

对于新创建的类实例。因此,在此示例中,可以通过以下方式获取新的初始化实例:

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,

。例如,

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

It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a

在Python中编码时,通常不要混合制表符和空格。这样做可能会导致 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.

,你的程序将崩溃。在编码时保持一致 - 选择使用制表符或空格缩进,并在整个程序中遵循您选择的约定。

Code Blocks and Indentation{#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.

行打印(&#39;登录...&#39;)和打印(&#39;密码错误。&#39;)是两个独立的代码块。这些恰好只有一行,但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-statement中的两个代码块都缩进了四个空格,这是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中,需要指出语句所属的代码块。例如,最终的打印(&#39;All done!&#39;)没有缩进,因此不是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{#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,如果是,则表明飞行是自由的并且跳出了elif条件。如果age不小于2,则检查下一个elif条件以查看age是否介于2和13之间。如果是,则打印相应的消息并跳出if / elif语句。如果if条件和elif条件都不为True,则它执行else块中的代码。

Conditional expressions{#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:

第二行中=右侧的表达式称为条件表达式,它的计算结果为&#39;yuck&#39;或&#39;yum&#39;。它相当于以下内容:

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语句短,但不够灵活或易于阅读。通常,您应该在使代码更简单时使用它们。

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,

Python中有八个比较操作。它们都具有相同的优先级(高于布尔操作的优先级)。比较可以任意链接;例如, 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).

被发现是假的)。

The following summarizes the comparison operations:

以下总结了比较操作:

OperationMeaning

OperationMeaning < 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

否定了对象的身份

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.

将复数与另一个内置数值类型进行比较时的异常,当对象具有无法比较的不同类型时,或者在没有定义排序的其他情况下。

Non-identical instances of a class normally compare as non-equal unless the class defines the

除非类定义了类,否则类的非相同实例通常会比较为不相等 __eq__() method.

方法。

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).

如果你想要比较运算符的常规含义,那就足够了。

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.

运营商无法定制;它们也可以应用于任何两个对象,并且永远不会引发异常。

We can also chain

我们也可以连锁 < and

和 > operators together. For instance,

运营商在一起例如, 3 < 4 < 5 will return

将返回 True , but

但是 3 < 4 > 5 will not. We can also chain the equality operator. For instance,

将不会。我们也可以链接相等运算符。例如, 3 == 3 < 5 will return

将返回 True but

但 3 == 5 < 5 will not.

将不会。

Equality Comparisons - "is" vs "=="{#equality-comparisons-is-vs-}

In Python, there are two comparison operators which allow us to check to see if two objects are equal. The

在Python中,有两个比较运算符允许我们检查两个对象是否相等。该 is operator and the

操作员和 == operator. However, there is a key difference between them!

运营商。但是,他们之间有一个关键的区别!

The key difference between 'is' and ' ' can be summed up as:

&#39;是&#39;和&#39;

&#39;之间的关键区别可以概括为:

  • is is used to compare identity
  • == is used to compare equality

Example{#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

&#39;运算符或&#39;is&#39;运算符,两者都将导致a True output.

输出。

>>> 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

输出。这是因为myListA和myListC是两个不同的变量,尽管包含相同的数据。即使它们看起来一样,它们也是如此 different .

>>> 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
  • An == expression outputs True if both variables contain the same data

A Dictionary (a.k.a "dict") in python is a built-in datatype that can be used to store

python中的Dictionary(又名"dict")是一种可用于存储的内置数据类型 key-value pairs. This allows you to treat a

对。这可以让你治疗一个 dict like it's a

喜欢它是一个 database to store and organize data.

存储和组织数据。

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.)

)然后它们可以互换使用来索引相同的字典条目。 (但请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)

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.

运算符用于从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:

keyword可用于检查dict中是否存在密钥:

>>> 'sanots' in teams
    False    
    >>> 'barcelona' in teams
    True
    >>> 'chelsea' not in teams
    False

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:

 类似资料: