Python Code Examples Python代码示例!

python code examples 学习python的一些例子。 html格式。 立即下载

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:

PythonCodeExample.zip 这是用Python编写的优秀源代码,无删改,多看看优秀的代码资源,会对Python学习有帮助的!如果无法下载,请联系我,内容摘自网络,包含对这些代码的描述。 立即下载

相关推荐

python_code_examples:通用PythonData Science示例笔记本和脚本

python_code_examples 我一直在写代码示例来展示人们的东西,我觉得是时候收集它们了。 我希望这些名字能自我解释。 如果有人希望我讲这些示例,请告诉我,我可以抛出有关这些示例或其他内容的youtube视频。 主要完成: 异步抓取 kmer分析和标记化(即将发表论文/谈话) 完全没有完成,需要评论: 网格搜索 隐马尔可夫模型与石榴在这里查看我有关HMM的内容,并简要介绍一下代码: : 甚至还没有清理,但是功能正常 NetworkX,建立网络并提高排名 黑杰克

初学者学习Python必知的7个网站

初学者学习Python必知的7个网站

Python单行客的博客 7855

Mac新手必看:用Homebrew安装wget的保姆级教程,附常见报错一键修复

本文为Mac新手提供使用Homebrew安装wget的详细教程,涵盖从Homebrew安装到wget基础使用的全流程,并附常见报错一键修复方案。通过本指南,用户可轻松掌握命令行下载工具wget的安装与使用技巧,解决Mac环境下资源下载的各种问题。

weixin_30635053的博客 367

初学者福利:分享五个免费的 Python 学习网站,抓紧收藏吧

最近有好多人说刚开始学习,有哪些免费的学习网站可以自学一下。于是,趁着周末的时间在各大网站上面梳理了一下找出了六个比较好的学习网站,并且都是免费的,比较适合初学者了解一些基础语法、解决BUG问题。如果是大佬的话了解一下就行了,废话不多说了直接上干货吧! 【阅读全文】 1、Python 官方中文网站 官方网站不仅有基础语法参考、Python标准模块介绍,相关的教程也有,平时查接口文档什么的都是比较方便的。 网站地址:https://docs.python.org/zh-cn/3/ 2、w3school 这是

梦在硅谷的博客 2万+

AI辅助发明专利撰写实战:30分钟高效生成高质量技术专利文档

在技术专利撰写领域,尤其是软件、算法或系统架构相关的发明专利,如何将创新的技术构思快速、规范地转化为符合《专利法》要求的申请文件,是许多开发者和技术团队面临的共同挑战。传统的人工撰写方式不仅耗时耗力,对撰写人的法律和技术双重背景要求极高,还容易因格式或术语不规范导致审查意见增多。本文将分享一套利用 AI 辅助工具,系统化、高效率地完成一篇高质量发明专利说明书撰写的实战流程。通过清晰的步骤拆解、可复制的提示词(Prompt)工程以及关键注意事项,即使是首次接触专利撰写的开发者,也能在短时间内掌握从技术方案梳理

子夜轻风 953

HTML5网页基础设计——课程介绍专栏

案例: 参考代码: <!doctype html> <html> <head> <meta charset="utf-8"> <title>动手实践</title> <style> *{ margin: 0; padding: 0; font-size:14px; } dd{ width: 461px; height: 145px; margin: -4px; pad.

shengming_tutou的博客 4594

FastAPI 声明请求示例数据:JSON Schema examples 与 openapi_examples 的完整用法与原理

如果你的 API 需要让前端、接口测试人员或下游调用方「一眼就知道该往 Body 里传什么」,那么**请求示例数据(Request Example Data)**就是最直接的沟通桥梁。本指南围绕 FastAPI 官方教程「Declare Request Example Data」(见 [docs/en/docs/tutorial/schema-extra-example.md](https://l

gitblog_00132的博客 358

FRM模型五:Brinson业绩归因

利用Brinson对基金组合业绩进行归因分析。

stonesssssss的博客 3006

Spike RISC-V 指令集模拟器完整上手指南:从安装到跑通第一个程序

Spike(riscv-isa-sim)是一款开源的 RISC-V 指令集模拟器,它让你的电脑直接运行 RISC-V 程序,不用开发板、不碰硬件。从安装到跑通第一个程序、看懂源码结构,这篇都讲到了。 ## 装它之前,环境要过关吗 🧰 Spike 是 C++ 写的,构建走经典的 configure + make 流程。系统上没门槛,但下面四样要先备齐: - 系统:Linux、macOS 或

gitblog_00291的博客 191

ESP-IDF的安装及其在VScode中编译环境的搭建

从安装目录的\Espressif\frameworks\esp-idf-v5.3.2\examples路径中拷贝一个工程到项目中,比如拷贝\get-started下的hello_world文件夹。安装时可能会遇到如下问题,提示:"e:\ssc\software\ESP-IDF\v5.3.2\Espressif\tools\idf-python\3.11.2\python.exe -m pip" is not valid. (ERROR_INVALID_PIP)接着等待安装完成即可,其他步骤同方式1。

Freddy_Ssc的博客 4369

视觉辅助RIS波束追踪:用摄像头“看见”用户,实现毫秒级波束对准

在无线通信领域,波束成形技术是提升高频段信号覆盖与质量的核心手段,其原理是通过调整天线阵列的相位,使信号能量在特定方向相干叠加,形成高增益定向波束。这项技术的价值在于能有效克服高频信号路径损耗大、穿透性差的瓶颈,广泛应用于5G/6G、毫米波通信及室内定位等场景。然而,传统波束追踪依赖信道估计或波束扫描,存在训练开销大、实时性差的问题。本文聚焦于一种创新解决方案:将计算机视觉与可重构智能表面(RIS)相结合。通过摄像头直接感知用户位置,并利用RIS快速重构反射波束方向,实现了近乎零开销、毫秒级延迟的波束追踪,

weixin_33552698的博客 620

AWS Code Examples 仓库 resources 目录全解析:跨服务示例的资源编排、基础设施与共享数据文件

`resources/` 是 aws-doc-sdk-examples 仓库中一个语言无关(language-agnostic)的公共资源层,集中存放跨服务示例运行所需的基础设施模板、前端客户端与共享数据文件。阅读本文后,你将掌握该目录四大子目录(`cdk`、`cfn`、`clients`、`sample_files`)的职责划分、各 CDK 应用创建的资源清单、三种运行 CDK 应用的方式(CD

gitblog_01152的博客 924

android 14.0 去掉usb授权提示框 默认给予权限

在14.0的系统rom产品开发中,在进行iot关于插入usb设备的开发过程中,在插入usb设备时会弹出usb授权提示框,也带来一些不便, 这个需要默认授予USB权限,插拔usb都不弹出usb弹窗所以这要从usb授权相关管理页默认给与usb权限,接下来分析下 相关的实现功能流程

安卓兼职framework和app工程师的博客 2261

PPT Master 示例工程(examples/)目录结构与可复现机制解析

> 本文围绕 [examples/README.md](https://link.gitcode.com/i/9a9e65350205487b637e58334cc009e6) 展开,系统讲解 PPT Master 仓库中示例工程(example project)的目录规范、文件职责、在线画廊数据源与本地预览方式,并结合真实工程(如 `ppt169_swiss_grid_systems`)和 `s

gitblog_00783的博客 355

ISP算法:自动白平衡(AWB)

1. 为什么要做白平衡? 人类视觉系统具有颜色恒常性特点,一次人类对物体观察不受光源影响。但是Sensor在不同光线下,物体呈现的颜色不同,在晴朗天空下会偏蓝,在烛光下会偏红。如图: 2.什么是自动白平衡? 为了消除光源对于图像传感器成像的影响,模拟人类视觉系统的颜色恒常性。保证在任何场景下看到的白色是真正的白色。 3. 如何做自动白平衡? 只要乘以一个对角矩阵,便可以进行白平衡...

a200800170331的专栏 1万+

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

QQ空间历史说说全量备份:一键把老说说导出成Excel和网页

QQ空间的说说散落在好多年里,手机上很难翻回当年的内容,官方也没有批量导出的入口。GetQzonehistory 就是专门做 QQ空间说说备份 的工具:扫码登录后,把你账号下所有可见、未删除的说说抓下来,在本机生成 Excel 表格和说说网页。照下面的步骤做,没写过代码也能跑完全程。 ## 结果在哪里:一次QQ空间说说全量备份包含哪些文件 跑完之后,全部结果都放在 `resource/resu

gitblog_01157的博客 466

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

AWS s3 python sdk code examples

Yet another easy-to-understand, easy-to-use aws s3 python sdk code examples.

Gary 的影响力 3285

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Agent Governance Toolkit 示例生态指南:基于 examples/AGENTS.md 的示例贡献规范、实践路径与仓库全景

本文围绕仓库根目录下 [examples/AGENTS.md](https://link.gitcode.com/i/32c42c0e99b8d53156e705f17480eac8) 这份编码 Agent 指令文档展开,系统讲解 Agent Governance Toolkit(AGT)中 `examples/` 目录的定位、示例贡献规范、质量边界与验证要求,并结合仓库内真实的 quicksta

gitblog_00982的博客 942

探索编程之美:code-examples开源项目推荐

探索编程之美:code-examples开源项目推荐 code-examples:项目的核心功能/场景 编程实例与代码片段库 在当今数字化时代,编程已经成为技术人员必备的核心技能之一。无论是初学者还是资深开发者,都经常需要寻找示例代码来帮助理解新的编程概念或解决实际问题。今天,我将向大家推荐一个开源项目——code-examples,这是一个集成了大量编程实例与代码片段的库,旨在帮助开发者快速掌握...

gitblog_01166的博客 328

Naive UI 类型安全组件开发指南

用 Vue 3 + TypeScript 做中后台,多半撞上过这类问题:组件 props 手写一遍,属性名打错要等上线才暴露;主题覆盖对象的字段写错,样式坏掉之前没有任何提示。Naive UI 是全量 TypeScript 编写的 Vue 3 组件库:90+ 组件都带完整类型定义,主题配置直接由编译器帮你检查。 ## 能力拆解 ### 90+ 组件全量有类型,拼错 props 当场报错 在编

gitblog_07930的博客 424

parse-video-py打包重构指南:uv + pyproject.toml可选依赖组,把视频去水印工具变成可安装Python包的实践

parse-video-py 是一款支持抖音、快手、哔哩哔哩、西瓜视频等 25+ 平台的视频去水印解析工具。这篇文章分享它如何用 uv 包管理器 + pyproject.toml 可选依赖组完成打包重构:从一个"只能克隆下来本地跑"的 Web 服务,变成一个可一键安装的 Python 包,新手也能照做。 ## 为什么 venv + requirements.txt 不够用?3个真实痛点 重构前

gitblog_00688的博客 846

Ship of Harkinian 安装教程:把时之笛搬上 PC,4K 60FPS 一次跑通

Ship of Harkinian(SOH)是基于《时之笛》反编译源码的现代重制版,让这台 1998 年的老游戏在 PC、Mac、Linux 上以 4K 宽屏、稳定 60FPS 运行,并自带 `.otr` Mod 生态。只要你手里有一份合法 ROM,跟着本文走,从下载到进游戏不会超过十分钟。 ## 🧰 动手前备齐:一张清单过完环境检查 SOH 不附带任何受版权保护的资源:游戏里的模型、贴图、

gitblog_00574的博客 148

测试驱动解题:用 advent-of-code-data 的 --example 自动获取示例数据验证答案

参加 Advent of Code(AoC)圣诞编程挑战时,最令人头疼的莫过于:代码在自己的完整输入上跑通了,却因为算法存在隐蔽 bug 而在提交时被判"答案错误"。**advent-of-code-data** 这个 Python 库提供的 `--example` 功能,能帮你自动获取题目自带的示例数据与参考答案,用**测试驱动**的方式先验证再提交,大幅减少无效提交和等待限流的痛苦。本文将完整

gitblog_00531的博客 822

难怪大家都建议我上这5个网站学Python!

这五个网站各具特色且广受好评,是学习Python的绝佳选择。无论是初学者还是有一定经验的程序员,都可以在这些网站上找到适合自己的学习资源和项目实践机会。这只是冰山一角,想要完整版的小伙伴下图获取~04,Python小白必备手册。03,Python面试集锦。01,Python大礼包。02,Python电子书。05,Python安装包。06,数据分析全套资源。

2301_78095812的博客 1209

PraisonAI examples 示例库实战指南:Agent-Centric API、Workflow 与 Serve 部署全解析

本篇指南基于 PraisonAI 仓库中的官方示例目录 [examples/](https://link.gitcode.com/i/a48d01bf80ab7305b526a57266f1ae16) 展开,系统讲解其目录结构、分类索引、Agent-Centric 统一参数(Consolidated Params)体系与 Serve 服务端示例。读完之后,你将知道如何快速定位并按需运行各类示例,理

gitblog_00031的博客 592

TensorFlow Lite 跨平台部署实战:从模型准备到 Android、iOS 推理全流程

把模型跑通容易,难的是从训练到上线的全链路:数据整理、模型转换、真机推理、性能调优,每一步都可能卡住你。TensorFlow examples 是 TensorFlow 官方的示例仓库,其中 TFLite 相关内容覆盖了图像分类、目标检测、手势识别等端侧 AI 场景,包含 Android、iOS 双平台的示例应用、TFLite Model Maker 模型训练与转换库,以及一步步带练的 codel

gitblog_01184的博客 185
上一篇: Python 开发植物大战僵尸游戏!
下一篇: 基于python的selenium两种文件上传操作 !
普通网友
博客等级 码龄7年 438粉丝 263原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值