大家好,小编来为大家解答以下问题,python编程300例pdf百度网盘,python编程入门经典pdf下载,今天让我们一起来看看吧!
本篇文章给大家谈谈python手册中文版pdf 百度云,以及python手册中文版 pdf神经网络CSDN,希望对各位有所帮助,不要忘了收藏本站喔PHP在我人生中的含义。
Source code download: 本文相关源码
学习目标:
文章目录
学习目标:1 front matter前言 1.1 Python is an easy to learn, powerful programming language.1.2 many free third party Python modules, programs and tools, and additional documentation1.3 utf-81.4 注释符号#2 解释器 as 计算器 The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.交互模式下,最近一次表达式输出保存在 _ 变量中。这意味着把 Python 当做桌面计算器使用时,可以方便的进行连续计算,例如: Like in C, the equal sign ("=") is used to assign a value to a variable. The value of an assignment is not written:There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:3.字符串string Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:可以在行加反斜杠做为继续符,这表示下一行是当前行的逻辑沿续Deepl降重。如果我们创建一个“行”("raw")字符串,\ n序列就不会转为换行,源码中的反斜杠和换行符n都会做为字符串中的数据处理Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.字符串可以用 + 号联接(或者说粘合),也可以用 * 号循环。字符串可以用下标(索引)查询;就像 C 一样,字符串的第一个字符下标是 0。 除了数值, Python 还可以通过几种不同的方法操作字符串。字符串用单引号或双引号标识:4.开始编程 First Steps Towards ProgrammingFibonacci series: 4.1 第一行包括了 复合参数:变量 a 和 b 同时被赋值为 0 和 1,然后a, b = b, a+b注意理解 。4.2 循环体是缩进的:缩进是 Python 对语句分组的方法。4.3 print 语句末尾的逗号避免了输出中的换行: 注意print b,4.4 insert()函数 python insert()函数用于将指定对象插入列表的指定位置。list.insert(index, obj)list.insert(index = -1, obj)除外,当index = -1时,是插在倒数第二位的,也就是:4.5 range() 函数 The range() Function4.6 break 和 continue 语句, 以及 循环中的 else 子句 break and continue Statements, and else Clauses on Loops 但循环被 break 中止的情况下不会执行。以下搜索素数的示例程序演示了这个子句:4.6 pass 语句 pass Statements4.8 自定义函数 Defining FunctionsNow call the function we just defined: 4.9 参数默认值 Default Argument Values 重要警告:默认值只会解析一次。当默认值是一个可变对象,诸如链表、字典或大部分类实例时,会产生一些差异。例如,以下函数在后继的调用中会累积它的参数值:4.10 关键字参数 Keyword Arguments 引入一个形如 **name 的参数时,它接收一个 字典 ,该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 *name 的形式参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式参数列表中的参数值。(*name 必须在 **name 之前出现) 例如,我们这样定义一个函数:()新的Python中不能这么用了,新Python中如下sorted(())4.11 参数列表的分拆 Unpacking Argument Lists以下内容看不懂以下内容看不懂5 数据结构 Data Structures 5.1 深入链表 More on Listsappend( x)extend( L)insert( i, x)remove( x)pop( [i])index( x)count( x)sort( )reverse( )5.1.1 把链表当作堆栈使用 Using Lists as Stacks5.1.2 把链表当作队列使用 Using Lists as Queues5.1.3 函数化编程工具 Functional Programming Tools5.1.4 链表推导式 List Comprehensions5.2 del 语句5.3 元组(Tuples)和序列(Sequences )Tuples and SequencesTuples may be nested: 5.4 Dictionaries 字典5.5 循环技巧 Looping Techniques5.6 深入条件控制 More on Conditions5.7 比较序列和其它类型 Comparing Sequences and Other Types6. 模块 ModulesFibonacci numbers module6.1 深入模块 More on Modules 6.1.1 模块搜索路径 The Module Search Path6.1.2 “编译”Python文件 ``Compiled'' Python filesSome tips for experts:6.2 标准模块 Standard Modules6.3 dir() 函数 dir() Function6.4 包 Packages 6.4.1 以 * 方式加载包 Importing * From a Package6.4.2 内置包(Intra-package)参考 Intra-package References6.4.3 多重路径中的包 Packages in Multiple Directories7. 输入和输出 Input and Output 7.1 设计输出格式 Fancier Output FormattingThe repr() of a string adds string quotes and backslashes:The argument to repr() may be any Python object:reverse quotes are convenient in interactive sessions: 7.2 读写文件 Reading and Writing Filesopen() returns a file object, and is most commonly used with two arguments: "open(filename, mode)".7.2.1 文件对象(file object)的方法 Methods of File Objects7.2.2 pickle 模块 pickle Module8. 错误和异常 Errors and Exceptions 8.1 异常 Exceptions8.2 处理异常 Handling Exceptions8.3 抛出异常 Raising Exceptions8.4 用户自定义异常 User-defined Exceptions8.5 定义清理行为 Defining Clean-up Actions9. 类 Classes 9.1 有关术语的话题 A Word About Terminology9.2 Python 作用域和命名空间 Python Scopes and Name Spaces9.3 初识类 A First Look at Classes9.4 一些说明 Random RemarksFunction defined outside the class 9.5 继承 Inheritance9.6 私有变量 Private Variables9.7 补充 Odds and EndsFill the fields of the record 9.8 异常也是类 Exceptions Are Classes Too以上没看 9.9 ==迭代器 Iterators ==9.10 生成器 Generators10. 标准库概览 Brief Tour of the Standard Library 10.1 操作系统概览 Operating System Interface10.2 文件通配符 File Wildcards10.3 命令行参数 Command Line Arguments10.4 错误输出重定向和程序终止 Error Output Redirection and Program Termination10.5 字符串正则匹配 String Pattern Matching10.6 数学 Mathematics10.7 互联网访问 Internet Access10.8 日期和时间 Dates and Timesdates are easily constructed and formatteddates support calendar arithmetic 10.9 数据压缩 Data Compression10.10 性能度量 Performance Measurement10.11 质量控制 Quality Control 提示:这里可以添加学习目标
例如:
一周掌握Python入门知识
1 front matter前言
1.1 Python is an easy to learn, powerful programming language.
1.2 many free third party Python modules, programs and tools, and additional documentation
1.3 utf-8
根据个人经验,推荐使用 cp-936或utf-8处理中文--译者注
1.4 注释符号#
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
2 解释器 as 计算器
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
交互模式下,最近一次表达式输出保存在 _ 变量中。这意味着把 Python 当做桌面计算器使用时,可以方便的进行连续计算,例如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>
Like in C, the equal sign (“=”) is used to assign a value to a variable. The value of an assignment is not written:
>>> width = 20
>>> height = 5*9
>>> width * height
900
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
Python完全支持浮点数,不同类型的操作数混在一起时,操作符会把整型转化为浮点数。
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
3.字符串string
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:
除了数值, Python 还可以通过几种不同的方法操作字符串。字符串用单引号或双引号标识:
可以在行加反斜杠做为继续符,这表示下一行是当前行的逻辑沿续。
如果我们创建一个“行”(“raw”)字符串,\ n序列就不会转为换行,源码中的反斜杠和换行符n都会做为字符串中的数据处理
Or, strings can be surrounded in a pair of matching triple-quotes: “”" or ‘’'. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.
字符串可以用 + 号联接(或者说粘合),也可以用 * 号循环。
字符串可以用下标(索引)查询;就像 C 一样,字符串的第一个字符下标是 0。
除了数值, Python 还可以通过几种不同的方法操作字符串。字符串用单引号或双引号标识:
‘spam eggs’ ‘spam eggs’ ‘doesn’t’ “doesn’t” “doesn’t” “doesn’t” ‘“Yes,” he said.’ ‘“Yes,” he said.’ ““Yes,” he said.” ‘“Yes,” he said.’ ‘“Isn’t,” she said.’ ‘“Isn’t,” she said.’
String literals can span multiple lines in several ways. Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line:
字符串可以通过几种方式分行。可以在行加反斜杠做为继续符,这表示下一行是当前行的逻辑沿续。
hello = “This is a rather long string containing\n several lines of text just as you would do in C.\n Note that whitespace at the beginning of the line is significant.”
print hello
Note that newlines would still need to be embedded in the string using \n; the newline following the trailing backslash is discarded. This example would print the following:
注意换行用 \n 来表示;反斜杠后面的新行标识(newline,缩写“n”)会转换为换行符,示例会按如下格式打印:
This is a rather long string containing several lines of text just as you would do in C. Note that whitespace at the beginning of the line is significant.
If we make the string literal a ``raw’’ string, however, the \n sequences are not converted to newlines, but the backslash at the end of the line, and the newline character in the source, are both included in the string as data. Thus, the example:
然而,如果我们创建一个“行”(“raw”)字符串,\ n序列就不会转为换行,源码中的反斜杠和换行符n都会做为字符串中的数据处理。如下所示:
hello = r"This is a rather long string containing\n several lines of text much as you would do in C."
print hello
would print:
会打印为:
This is a rather long string containing\n several lines of text much as you would do in C.
Or, strings can be surrounded in a pair of matching triple-quotes: “”" or ‘’'. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.
另外,字符串可以用一对三重引号”””或’''来标识。三重引号中的字符串在行尾不需要换行标记,所有的格式都会包括在字符串中。
print “”" Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to “”"
produces the following output:
生成以下输出:
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it’s enclosed in single quotes. (The print statement, described later, can be used to write strings without quotes or escapes.)
解释器打印出来的字符串与它们输入的形式完全相同:内部的引号,用反斜杠标识的引号和各种怪字符,都精确的显示出来。如果字符串中包含单引号,不包含双引号,可以用双引号引用它,反之可以用单引号。(后面介绍的 print 语句,可以在不使用引号和反斜杠的情况下输出字符串)。
Strings can be concatenated (glued together) with the + operator, and repeated with *:
字符串可以用 + 号联接(或者说粘合),也可以用 * 号循环。
word = ‘Help’ + ‘A’ word ‘HelpA’ ‘<’ + word*5 + ‘>’ ‘’
Two string literals next to each other are automatically concatenated; the first line above could also have been written “word = ‘Help’ ‘A’”; this only works with two literals, not with arbitrary string expressions:
两个字符串值之间会自动联接,上例第一行可以写成“word = ‘Help’ ‘A’”。这种方式只对字符串值有效,任何字符串表达式都不适用这种方法。
‘str’ ‘ing’ # <- This is ok ‘string’ ‘str’.strip() + ‘ing’ # <- This is ok ‘string’ ‘str’.strip() ‘ing’ # <- This is invalid File “”, line 1, in ? ‘str’.strip() ‘ing’ ^ SyntaxError: invalid syntax
Strings can be subed (indexed); like in C, the first character of a string has sub (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.
字符串可以用下标(索引)查询;就像 C 一样,字符串的第一个字符下标是 0。这里没有独立的字符类型,字符仅仅是大小为一的字符串。就像在 Icon 中那样,字符串的子串可以通过切片标志来表示:两个由冒号隔开的索引。
word[4] ‘A’ word[0:2] ‘He’ word[2:4] ‘lp’
4.开始编程 First Steps Towards Programming
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:
当然,我们可以用 Python 做比2加2更复杂的事。例如,我们可以用以下的方法输出菲波那契(Fibonacci)序列的子序列:
Fibonacci series:
… # the sum of two elements defines the next … a, b = 0, 1
while b < 10: … print b … a, b = b, a+b … 1 1 2 3 5 8
This example introduces several new features.
示例中介绍了一些新功能:
4.1 第一行包括了 复合参数:变量 a 和 b 同时被赋值为 0 和 1,然后a, b = b, a+b注意理解 。
最后一行又一次使用了这种技术,证明了在赋值之前表达式右边先进行了运算。右边的表达式从左到右运算。
while 循环运行在条件为真时执行(这里是 b < 10 )。在 Python 中,类似于 C 任何非零值为真,零为假。这个条件也可以用于字符串或链表,事实上于对任何序列类型,长度非零时为真,空序列为假。示例所用的是一个简单的比较。标准的比较运算符写法和 C 相同: < (小于),> (大于),== (等于),<= (小于等于),>=(大于等于)和 != (不等于)。
4.2 循环体是缩进的:缩进是 Python 对语句分组的方法。
Python 还没有提供一个智能编辑功能,你要在每一个缩进行输入一个 tab 或(一个或多个)空格。实际上你可能会准备更为复杂的文本编辑器来编写你的 Python 程序,大多数文本编辑器都提供了自动缩进功能。交互式的输入一个复杂语句时,需要用一个空行表示完成(因为解释器没办法猜出你什么时候输入最后一行)。需要注意的是每一行都要有相同的缩进来标识这是同一个语句块。
4.3 print 语句末尾的逗号避免了输出中的换行: 注意print b,
a, b = 0, 1 while b < 1000: … print b, … a, b = b, a+b … 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Note that
4.4 insert()函数
python insert()函数用于将指定对象插入列表的指定位置。
list.insert(index, obj)
1 参数:
index:对象obj需要插入的索引位置。
obj:要插入列表中的对象。
共有如下5种场景:
1:index=0时,从头部插入obj。
2:index > 0 且 index < len(list)时,在index的位置插入obj。
3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如:-1 表示从倒数第1位插入obj。
4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj。
5:当index >= len(list)时,从尾部插入obj。
list.insert(index = -1, obj)除外,当index = -1时,是插在倒数第二位的,也就是:
lst = [2,2,2,2,2,2] lst.insert(-1,6) print(lst) 1 2 3
[2, 2, 2, 2, 2, 6, 2]
例如(没有暗指):
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print x, len(x)
...
cat 3
window 6
defenestrate 12
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient:
在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这样的情况)。如果你想要修改你迭代的序列(例如,复制选择项),你可以迭代它的复本。通常使用切片标识就可以很方便的做到这一点:
>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
4.5 range() 函数 The range() Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:
如果你需要一个数值序列,内置函数range()可能会很有用,它生成一个等差级数链表。
range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list; range(10) generates a list of 10 values, exactly the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the `step’):
range(10) 生成了一个包含10个值的链表,它准确的用链表的索引值填充了这个长度为10的列表,所生成的链表中不包括范围中的结束值。也可以让range操作从另一个数值开始,或者可以指定一个不同的步进值(甚至是负数,有时这也被称为“步长”):
range(5, 10) [5, 6, 7, 8, 9] range(0, 10, 3) [0, 3, 6, 9] range(-10, -100, -30) [-10, -40, -70]
To iterate over the indices of a sequence, combine range() and len() as follows:
需要迭代链表索引的话,如下所示结合使 用range() 和 len() :
a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’] for i in range(len(a)): … print i, a[i] … 0 Mary 1 had 2 a 3 little 4 lamb
4.6 break 和 continue 语句, 以及 循环中的 else 子句 break and continue Statements, and else Clauses on Loops
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
break 语句和 C 中的类似,用于跳出最近的一级 for 或 while 循环。
The continue statement, also borrowed from C, continues with the next iteration of the loop.
continue 语句是从 C 中借鉴来的,它表示循环继续执行下一次迭代。
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
循环可以有一个 else 子句;它在循环迭代完整个列表(对于 for )或执行条件为 false (对于 while )时执行,
但循环被 break 中止的情况下不会执行。以下搜索素数的示例程序演示了这个子句:
for n in range(2, 10): … for x in range(2, n): … if n % x == 0: … print n, ‘equals’, x, ‘*’, n/x … break … else: … # loop fell through without finding a factor … print n, ‘is a prime number’ … 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
4.6 pass 语句 pass Statements
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
pass 语句什么也不做。它用于那些语法上必须要有什么语句,但程序什么也不做的场合,例如:
while True: … pass # Busy-wait for keyboard interrupt …
4.8 自定义函数 Defining Functions
We can create a function that writes the Fibonacci series to an arbitrary boundary:
def fib(n): # write Fibonacci series up to n … “”“Print a Fibonacci series up to n.”“” … a, b = 0, 1 … while b < n: … print b, … a, b = b, a+b …
Now call the function we just defined:
… fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
以下示例演示了如何从函数中返回一个包含菲波那契数列的数值链表,而不是打印它:
def fib2(n): # return Fibonacci series up to n … “”“Return a list containing the Fibonacci series up to n.”“” … result = [] … a, b = 0, 1 … while b < n: … result.append(b) # see below … a, b = b, a+b … return result … f100 = fib2(100) # call it f100 # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
This example, as usual, demonstrates some new Python features:
4.9 参数默认值 Default Argument Values
默认值在函数定义段被解析,如下所示:
i = 5
def f(arg=i):
print arg
i = 6
f()
will print 5.
以上代码会打印5。
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
重要警告:默认值只会解析一次。当默认值是一个可变对象,诸如链表、字典或大部分类实例时,会产生一些差异。例如,以下函数在后继的调用中会累积它的参数值:
如下函数f(1)后L=[]不再为空,如想为空则只能函数中重命名如下下
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
This will print
这会打印出:
[1] [1, 2] [1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
如果你不想在不同的函数调用之间共享参数默认值,可以如下面的实例一样编写函数:
def f(a, L=None): if L is None: L = [] L.append(a) return L
4.10 关键字参数 Keyword Arguments
Functions can also be called using keyword arguments of the form “keyword = value”. For instance, the following function:
函数可以通过关键字参数的形式来调用,形如"keyword = value"。例如,以下的函数:
def parrot(voltage, state=‘a stiff’, action=‘voom’, type=‘Norwegian Blue’): print “-- This parrot wouldn’t”, action, print “if you put”, voltage, “Volts through it.” print “-- Lovely plumage, the”, type print “-- It’s”, state, “!”
could be called in any of the following ways:
可以用以下的任一方法调用:
parrot(1000) parrot(action = ‘VOOOOOM’, voltage = 1000000) parrot(‘a thousand’, state = ‘pushing up the daisies’) parrot(‘a million’, ‘bereft of life’, ‘jump’)
but the following calls would all be invalid:
不过以下几种调用是无效的:
parrot() # required argument missing parrot(voltage=5.0, ‘dead’) # non-keyword argument following keyword parrot(110, voltage=220) # duplicate value for argument parrot(actor=‘John Cleese’) # unknown keyword
In general, an argument list must have any positional arguments followed by any keyword arguments, where the keywords must be chosen from the formal parameter names. It’s not important whether a formal parameter has a default value or not. No argument may receive a value more than once – formal parameter names corresponding to positional arguments cannot be used as keywords in the same calls. Here’s an example that fails due to this restriction:
通常,参数列表中的每一个关键字都必须来自于形式参数,每个参数都有对应的关键字。形式参数有没有默认值并不重要。实际参数不能一次赋多个值——形式参数不能在同一次调用中同时使用位置和关键字绑定值。这里有一个例子演示了在这种约束下所出现的失败情况:
def function(a): … pass … function(0, a=0) Traceback (most recent call last): File “”, line 1, in ? TypeError: function() got multiple values for keyword argument ‘a’
引入一个形如 **name 的参数时,它接收一个 字典 ,该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 *name 的形式参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式参数列表中的参数值。(*name 必须在 **name 之前出现) 例如,我们这样定义一个函数:
()新的Python中不能这么用了,新Python中如下sorted(())
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, '?')
print("-- I'm sorry, we're all out of", kind)
for arg in arguments: print(arg)
print('-'*40)
keys = ()
# ()新的Python中不能这么用了,新Python中如下sorted(())
sorted(())
for kw in keys: print(kw, ':', keywords[kw])
cheeseshop('Limburger', 'Its very runny222, sir.',
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
and of course it would print:
当然它会按如下内容打印:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
4.11 参数列表的分拆 Unpacking Argument Lists
另有一种相反的情况: 当你要传递的参数已经是一个列表但要调用的函数却接受分开一个个的参数值. 这时候你要把已有的列表拆开来. 例如内建函数 range() 需要要独立的 start, stop 参数. 你可以在调用函数时加一个 * 操作符来自动把参数列表拆开:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
以下内容看不懂
以下内容看不懂
4.7.3 可变参数表 Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal arguments may occur.
最后,一个最不常用的选择是可以让函数调用可变个数的参数。这些参数被包装进一个元组。在这些可变个数的参数之前,可以有零到多个普通的参数:
def fprintf(file, format, *args):
file.write(format % args)
4.7.4 参数列表的分拆 Unpacking Argument Lists
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:
另有一种相反的情况: 当你要传递的参数已经是一个列表但要调用的函数却接受分开一个个的参数值. 这时候你要把已有的列表拆开来. 例如内建函数 range() 需要要独立的 start, stop 参数. 你可以在调用函数时加一个 * 操作符来自动把参数列表拆开:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
4.7.5 Lambda 形式 Lambda Forms
By popular demand, a few features commonly found in functional programming languages and Lisp have been added to Python. With the lambda keyword, small anonymous functions can be created. Here's a function that returns the sum of its two arguments: "lambda a, b: a+b". Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:
出于实际需要,有几种通常在功能性语言和 Lisp 中出现的功能加入到了 Python 。通过 lambda 关键字,可以创建短小的匿名函数。这里有一个函数返回它的两个参数的和:"lambda a, b: a+b"。 Lambda 形式可以用于任何需要的函数对象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从包含范围内引用变量:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>>
原文地址1:https://blog.csdn.net/2301_81837718/article/details/135890417
参考资料:python中用turtle画一个圆形 https://blog.csdn.net/SXIAOYAN_/article/details/140061099