输入——>处理——>输出
函数取名注意事项:
- 首先,名称不能以数字开头。能用在名称开头的有,大小写字母和下划线
_
;- 其次,名称中不能有空格,要么使用下划线连接词汇,如,
do_nothing
,要么使用 Camel Case,如doNothing
—— 更推荐使用下划线;- 再次,名称不能与关键字重合
没有return()语句的函数的返回值是None
在一个 位置参数 (Positional Arguments)前面标注了星号,*
,那么,这个位置参数可以接收一系列值,在函数内部可以对这一系列值用 for ... in ...
循环进行逐一的处理。
带一个星号的参数,英文名称是 “Arbitrary Positional Arguments”
def say_hi(*names):
for name in names:
print(f‘Hi, {name}!‘)
say_hi()
say_hi(‘ann‘)
say_hi(‘mike‘, ‘john‘, ‘zeo‘)
注意:一个函数中,可以接收一系列值的位置参数只能有一个;并且若是还有其它位置参数存在,那就必须把这个可以接收一系列值的位置参数排在所有其它位置参数之后。
可以在定义函数的时候,为某些参数设定默认值,这些有默认值的参数,又被称作关键字参数(Keyword Arguments)。从这个函数的 “用户” 角度来看,这些设定了默认值的参数,就成了 “可选参数”。
def say_hi(greeting, *names, capitalized=False):
for name in names:
if capitalized:
name = name.capitalize() # capitalize()使字符的第一个字母大写
print(f‘{greeting}, {name}!‘)
say_hi(‘Hello‘, ‘mike‘, ‘john‘, ‘zeo‘)
say_hi(‘Hello‘, ‘mike‘, ‘john‘, ‘zeo‘, capitalized=True)
可以接收很多值的关键字参数(Arbitrary Keyword Argument),在处理接收到的 Arbitrary Keyword Argument 时,用的是对字典的迭代方式。
def say_hi(**names_greetings):
for name, greeting in names_greetings.items():
print(f‘{greeting}, {name}!‘)
a_dictionary = {‘mike‘:‘Hello‘, ‘ann‘:‘Oh, my darling‘, ‘john‘:‘Hi‘}
say_hi(**a_dictionary)
say_hi(**{‘mike‘:‘Hello‘, ‘ann‘:‘Oh, my darling‘, ‘john‘:‘Hi‘})
Order of Arguments
- Positional
- Arbitrary Positional
- Keyword
- Arbitrary Keyword
sort()
与list.sort()
sort()
与list.sort()
的用法(看看官方文档有好处)
Key Functions
Both
list.sort()
andsorted()
have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.>>> sorted("This is a test string from Andrew".split(), key=str.lower) [‘a‘, ‘Andrew‘, ‘from‘, ‘is‘, ‘string‘, ‘test‘, ‘This‘]
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
>>> student_tuples = [ ... (‘john‘, ‘A‘, 15), ... (‘jane‘, ‘B‘, 12), ... (‘dave‘, ‘B‘, 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The
operator
module hasitemgetter()
,attrgetter()
, and amethodcaller()
function.>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2)) [(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
>>> sorted(student_objects, key=attrgetter(‘age‘)) [(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
Both
list.sort()
andsorted()
accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order:>>> sorted(student_tuples, key=itemgetter(2), reverse=True) [(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]
>>> sorted(student_objects, key=attrgetter(‘age‘), reverse=True) [(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]
key的参数是函数,可以利用lambda来构建。
def add(x, y):
return x + y
add(3, 5)
上述程序用lambda
表示如下
add = lambda x, y: x + y
add(3, 5)
lambda
的语法结构如下:
lambda_expr ::= "lambda" [parameter_list] ":" expression
注意:lambda
语句中,:
之后有且只能有一个表达式。
以阶乘(factorial)的程序来理解递归
n! = n × (n-1) × (n-2)... × 1
- 即,
n! = n × (n-1)!
- 且,
n >= 1
def factorial(n):
if n == 1: return 1
elif n > 1: return n*factorial(n-1)
print(factorial(5))
递归三原则:
- 根据定义,递归函数必须在内部调用自己;
- 必须设定一个退出条件;
- 递归过程中必须能够逐步达到退出条件……
原文:https://www.cnblogs.com/augustine0654/p/14683413.html