一、作业内容
笨办法学 Python 习题18-26以及加分题。
二、作业代码:
# 习题 18:命名、变量、代码、函数
# 知识点总结:
# 一、函数可以给代码片段命名,就跟变量和数字命名一样
# 二、它们可以接受参数,就跟你的脚本接受argv一样。
# 三、通过使用#1和#2,它们可以让你创建微型脚本或者小命令。
# this one is like your scripts with argv
# 用def定义函数print_two,参数为*args
def print_two(*args):
# 将args解包,将所有的参数依次赋予左边的变量名
arg1, arg2 = args
# 打印包含格式化变量的字符串arg1: %r, arg2: %r ,变量名分别为arg1和arg2
print("arg1: %r, arg2: %r" % (arg1, arg2))
# ok, that *args is actually pointless, we can just do this
# 用def定义函数print_two_again,参数分别为arg1和arg2
def print_two_again(arg1, arg2):
# 打印包含格式化变量的字符串 arg1: %r, arg2: %r,变量名分别为arg1和arg2
print("arg1: %r, arg2: %r" % (arg1, arg2))
# this just takes one argument
# 用def定义函数print_one,参数为arg1
def print_one(arg1):
# 打印包含格式化变量的字符串 arg:1 %r,变量名为arg1
print("arg:1 %r" % arg1)
# this one takes no arguments
# 用def定义函数print_none
def print_none():
# 打印字符串I got mothin.
print("I got mothin.")
# 调用函数print_two(),参数为字符串Zed,字符串Shaw
print_two("Zed", "Shaw")
# 调用函数print_two_again(),参数为字符串Zed,字符串Shaw
print_two_again("Zed", "Shaw")
# 调用函数print_one(),参数为字符串First!
print_one("First!")
# 调用函数print_none()
print_none()
运行结果如下:
"C:\Program Files\Python36\python.exe" E:/python3_project/ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg:1 'First!'
I got mothin.
Process finished with exit code 0
加分习题
为自己写一个函数注意事项以供后续参考。你可以写在一个索引卡片上随时阅读,直到你记住所有的要点为止。注意事项如下:
1.函数定义是以 def 开始的吗?
是。
2.函数名称是以字符和下划线 _ 组成的吗?
不一定。函数名称可以是字符(不一定需要下划线),能体现出函数的功能就够了。
3.函数名称是不是紧跟着括号 ( ?
是。
4.括号里是否包含参数?多个参数是否以逗号隔开?
是。
5.参数名称是否有重复?(不能使用重复的参数名)
否。
6.紧跟着参数的是不是括号和冒号 ): ?
是。
7.紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent)?
是。
8.函数结束的位置是否取消了缩进 (“dedent”)?
是。
当你运行(或者说“使用 use”或者“调用 call”)一个函数时,记得检查下面的要点:
1.调运函数时是否使用了函数的名称?
2.函数名称是否紧跟着 ( ?
3.括号后有无参数?多个参数是否以逗号隔开?
4.函数是否以 ) 结尾?
# 习题19:函数和变量
# 创建名称为cheese_and_crackers函数,
# 参数分别为 cheese_count 和boxes_of_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# 打印包含格式化变量的字符串,变量名为cheese_count
print("You have %d cheeses!" % cheese_count)
# 打印包含格式化变量的字符串,变量名为boxes_of_crackes
print("You have %d boxes of crackers!" % boxes_of_crackers)
# 打印字符串 Man that's enough for a party!
print("Man that's enough for a party!")
# 打印字符串 Get a blanket并换行
print("Get a blanket.\n")
# 打印字符串 We can just give the function numbers directly:
# 调用函数cheese_and_crackers,变量名分别是20,30
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
# 打印字符串
# 将整数10、50分别赋值给变量 amount_of_cheese和amount_of_crackers
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
# 调用函数 cheese_and_crackers 变量名分别是amount_of_cheese, amount_of_crackers
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# 打印字符串 We can even do math inside too:
# 调用函数cheese_and_crackers,变量名分别是整数10与20的和,整数5与6的和
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
# 打印字符串 And we can combine the two, variables and math
# 调用函数 cheese_and_crackers,
# 第一个变量名为变量amount_of_cheese 与整数 100的和
# 第一个变量名为amount_of_crackers 与整数1000的和
print("And we can combine the two, variables and math.")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
运行结果如下:
"C:\Program Files\Python36\python.exe" E:/python3_project/ex19.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.
OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.
We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.
And we can combine the two, variables and math.
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.
Process finished with exit code 0
加分习题
1.倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。
2.从最后一行开始,倒着阅读每一行,读出所有的重要字符来。
3.自己编至少一个函数出来,然后用10种方法运行这个函数。
# 习题 20: 函数和文件
# 通过from...inport...导入sys模组,将argv直接导入程序
from sys import argv
# 将argv解包,将所有的参数依次赋予左边的变量名
script, input_file = argv
# 用def定义函数print_all,参数为f
def print_all(f):
# 在f上调用read()函数,无需任何参数。读取文本的内容并打印出来
print(f.read())
# 用def定义函数rewind,参数为f
def rewind(f):
# 在f上调用seek()函数
f.seek(0)
# 用def定义函数print_a_line(),参数分别为line_count和f
def print_a_line(line_count, f):
# 打印变量line_count.
# 在f上调用readline()函数,无需任何参数。读取文本文件中的一行,并打印出来
print(line_count, f.readline())
# open()函数用于打开文件,括号内为输入参数,参数为文件名,并存放到变量 current_file
current_file = open(input_file)
# 打印字符串 First let's print the whole file:\n
print("First let's print the whole file:\n")
# 调用函数print_all(),参数为current_file
print_all(current_file)
# 打印字符串 Now let's rewind, kind of like a tape.
print("Now let's rewind, kind of like a tape.")
# 调用函数 rewind(),参数为current_file
rewind(current_file)
# 打印字符串 Let's print three lines:
print("Let's print three lines:")
# 将整数1赋值给变量 current_line
current_line = 1
# 调用函数 print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
# 将变量 current_line 的值和整数1相加运算,并把结果存放到变量 current_line
current_line = current_line + 1
# 调用函数print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
# 将变量 current_line 的值和整数1相加运算,并把结果存放到变量 current_line
current_line = current_line + 1
# 调用函数print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
命令行运行结果如下:
E:\python3_project>python ex20.py filename.txt
First let's print the whole file:
To all the people out there.
I say I don't like my hair.
I need to share it off.
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to share it off.
加分习题
1.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。
2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。在每次调用函数时,打印出 current_line 的值,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。
3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。
4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。
5.研究一下 += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。
# 加分习题1.2.3.4.
# 通过from...inport...导入sys模组,将argv直接导入程序
from sys import argv
# 将argv解包,将所有的参数依次赋予左边的变量名
script, input_file = argv
# 用def定义函数print_all,参数为f
def print_all(f):
# 在f上调用read()函数,无需任何参数。读取文本的内容并打印出来
print(f.read())
# 用def定义函数rewind,参数为f
def rewind(f):
# 1.在f上调用fp.seek(offset, from_what)函数,fp是正在使用的文件指针,offset是移动多少位置,from_what定义参考点
# 2.关于参考点,0:表示参考点是文件的开头 1:参考点是当前的文件位置 2:表示参考点是文件的结尾
# 3.如果省略,from_what默认为0
f.seek(0)
# 用def定义函数print_a_line(),参数分别为line_count和f
def print_a_line(line_count, f):
# 打印变量line_count.
# 在f上调用readline()函数,无需任何参数。读取文本文件中的一行,并打印出来
print(line_count, f.readline())
# open()函数用于打开文件,括号内为输入参数,参数为文件名,并存放到变量 current_file
current_file = open(input_file)
# 打印字符串 First let's print the whole file:\n
print("First let's print the whole file:\n")
# 调用函数print_all(),参数为current_file
print_all(current_file)
# 打印字符串 Now let's rewind, kind of like a tape.
print("Now let's rewind, kind of like a tape.")
# 调用函数 rewind(),参数为current_file
rewind(current_file)
# 打印字符串 Let's print three lines:
print("Let's print three lines:")
# 将整数1赋值给变量 current_line
current_line = 1
# 调用函数 print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
# 将变量 current_line 的值和整数1相加运算,并把结果存放到变量 current_line
current_line = current_line + 1
# 调用函数print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
# 将变量 current_line 的值和整数1相加运算,并把结果存放到变量 current_line
current_line = current_line + 1
# 调用函数print_a_line(),参数为current_line, current_file
print_a_line(current_line, current_file)
# 习题 21: 函数可以返回东西
def add(a, b):
print("ADDING %d + %d" % (a, b))
return a + b
def subtract(a, b):
print("SUBTRACTING %d - %d" % (a, b))
return a - b
def multiply(a, b):
print("MULTIPLYING %d * %d" % (a, b))
return a * b
def divide(a, b):
print("DIVIDING %d / %d" % (a, b))
return a / b
print("Let's to some math with just funcitons!")
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print("Age: %d, Height: %d, Weight: %d, IQ: %(age, height, weight, iq")
# A puzzle for the extra creadit, type it in anyway.
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
运行结果如下:
"C:\Program Files\Python36\python.exe" E:/python3_project/ex21.py
Let's to some math with just funcitons!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: %d, Height: %d, Weight: %d, IQ: %(age, height, weight, iq
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes: -4391.0 Can you do it by hand?
Process finished with exit code 0
加分习题
1.如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。
2.这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。
3.一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。
4.最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。
习题 22: 到现在你学到了哪些东西?
首先,回到你的每一个习题的脚本里,把你碰到的每一个词和每一个符号(symbol,character的别名)写下来。确保你的符号列表是完整的。
符号列表
习题 23: 读代码
一边一读边做《简明 Python 教程》的练习。
# 习题 24: 更多练习
print("Let's practice everything.")
print('You\'d need to know \'about escapes with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - 2 + 3 - 6
print("This should be five: %s" % five)
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print("With a starting point of: %d" % start_point)
print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))
start_point = start_point / 10
print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
运行结果如下:
"C:\Program Files\Python36\python.exe" E:/python3_project/ex24.py
Let's practice everything.
You'd need to know 'about escapes with \ that do
newlines and tabs.
--------------
The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation
where there is none.
--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.
Process finished with exit code 0
加分习题
记得仔细检查结果,从后往前倒着检查,把代码朗读出来,在不清楚的位置加上注释。
故意把代码改错,运行并检查会发生什么样的错误,并且确认你有能力改正这些错误。
# 习题 25: 更多更多的练习
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.splif(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping if off."""
word = words.pop(0)
print(word)
def print_last_word(words):
"""Prints the Last word after popping it off."""
word = words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes in full sentence and returns the sorted word."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and Last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and Last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
命令行运行结果报错:
C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'ex25'
查了下Stack Overflow,有个哥们问了同样的问题,一位热心的答主解了惑:
因为我的文件路径不在系统路径上,因此Python不知道我的ex25模块可以在哪里找到。
再一次于命令行中运行,这一次出现了新的问题:
C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append(r'E:\python3_project')
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
Traceback (most recent call last):
File "", line 1, in
File "E:\python3_project\ex25.py", line 7, in break_words
words = stuff.splif(' ')
AttributeError: 'str' object has no attribute 'splif'
♂️没看清把split 打成了splif 。再来一次:
C:\Windows\system32>python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append(r'E:\python3_project')
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sort_words = ex25.sort_words(words)
>>> sort_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
File "", line 1, in
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word()
Traceback (most recent call last):
File "", line 1, in
TypeError: print_first_word() missing 1 required positional argument: 'words'
>>> ex25.print_first_word(sort_words)
All
>>> ex25.print_last_word(sort_words)
who
>>> sort_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>>
加分习题
1.研究答案中没有分析过的行,找出它们的来龙去脉。确认自己明白了自己使用的是模组 ex25 中定义的函数。
2.试着执行 help(ex25) 和 help(ex25.break_words) 。这是你得到模组帮助文档的方式。 所谓帮助文档就是你定义函数时放在 """ 之间的东西,它们也被称作 documentation comments (文档注解),后面你还会看到更多类似的东西。
3.重复键入 ex25. 是很烦的一件事情。有一个捷径就是用 from ex25 import * 的方式导入模组。这相当于说:“我要把 ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,开一个新的会话,看看你所有的函数是不是已经在那里了。
4.把你脚本里的内容逐行通过 python 编译器执行,看看会是什么样子。你可以执行CTRL-D (Windows 下是 CTRL-Z)来关闭编译器。
# 加分习题1.
# 此练习需要在命令行中先输入以下内容:
# >>>import sys
# >>>sys.path.append(r'E:\python3_project')
# >>>import ex25
# 用def定义函数 break_words,参数为stuff
# 在stuff上调用split()函数,参数为 ' ',并存放到变量words
# 返回变量words的值
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
# 用def定义函数 sort_words(),参数为words
# 调用sorted()函数对参数进行排序,并将值返回
def sort_words(words):
"""Sorts the words."""
return sorted(words)
# 用def定义函数 print_first_word(),参数为words
# 在words上调用pop() 函数用于移除列表中的一个元素(默认最后一个元素),参数为0(第一个元素)。并且返回该元素的值。并存放到变量word
# 打印变量word
def print_first_word(words):
"""Prints the first word after popping if off."""
word = words.pop(0)
print(word)
# 用def定义函数 print_last_word,参数为words
# 在words上调用pop() 函数用于移除列表中的一个元素(默认最后一个元素),参数为-1(最后一个元素)。并且返回该元素的值。并存放到变量word
# 打印变量word
def print_last_word(words):
"""Prints the Last word after popping it off."""
word = words.pop(-1)
print(word)
# 用def定义函数 sort_sentence,参数为 sentence
# 调用函数 sort_sentence,参数为 sentence,并将结果存放到变量 words
# 调用函数 sort_words,参数为 words,并将结果返回
def sort_sentence(sentence):
"""Takes in full sentence and returns the sorted word."""
words = break_words(sentence)
return sort_words(words)
# 用def定义函数 print_first_and_last,参数为 sentence
# 调用函数 break_words,参数为sentence,并将结果存放到变量 words
# 调用函数 print_first_word,参数为 words
# 调用函数 print_last_word,参数为 words
def print_first_and_last(sentence):
"""Prints the first and Last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
# 用def定义函数 print_first_and_last_sorted,参数为 sentence
# 调用函数 sort_sentence,参数为sentence,并将结果存放到变量 words
# 调用函数 print_first_word,参数为 words
# 调用函数 print_last_word,参数为 words
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and Last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# 习题 26: 恭喜你,现在可以考试了!
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print(word)
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
print("Let's practice everything.")
print('You\'d need to know\'bout escapes with\\that do\nnewlines and\ttabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - 2 + 3 - 5
print("This should be five: %s" % five)
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print("With a starting point of: %d" % start_point)
print("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))
start_point = start_point / 10
print("We can also do that this way:")
print("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))
sentence = "All god\tthings come to those who weight."
words = break_words(sentence)
sorted_words = sort_words(words)
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print(sorted_words)
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
这个练习的目的不是写程序,而是修正现有的程序……
三、学习总结
- 练习的过程中,遇到的很多问题已在作业内容(注释)中解释清楚。
- 实在不理解可以上 Stack Overflow 寻找帮助,不过新手遇到的绝大多数问题都可以找到问题和答案参考。
- 这周的作业有一半是在 Pythonista 3 上完成的,通勤时无聊打开做做练习什么的,这个应用非常强大,也非常好用!
下面是一些细节的补充,主要是做习题的过程中难以理解的部分:
习题 21 里出现了return
这个概念。可以看看这个知乎问题,很容易理解。
习题 25 中的pop()
函数和sorted()
函数,下面的相关练习,帮助理解:
pop()函数
classmates = ['bob', 'about', 'Zoo', 'Credit']
print(classmates)
# 要删除list末尾的元素,用pop()方法:
classmates.pop()
print(classmates)
# 删除指定位置的元素,用pop(i)方法,i是索引位置:
classmates.pop(1)
print(classmates)
# 排序算法
# 使用 Python 内置函数 sorted()就可以对list进行排序
print(sorted([36, 5, -12, 9, -21]))
# 接受一个 key 函数来实现自定义的排序,例如按绝对值大小排序:
print(sorted([36, 5, -12, 9, -21], key=abs))
# 默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果大写字母Z会排在小写字母a的前面
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
# 用key函数把字符串映射为忽略大小写排序即可,忽略大小写来比较两个字符串,实际上就是先把字富川都变成大写(或者都变成小写),再比较。
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
# 反向排序,不必改动key函数,可以传入第三个参数reverse=True
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))