预备知识
英文标点
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> type(string.punctuation)
<class 'str'>
>>>
list.count()方法
返回对应值的次数
string.strip()、lower()、split()方法
strip 去掉首位空格,与chars字符
lower小写
split分割字符
lambda表达式
匿名表达式
可以看成是简单版的函数。没有函数名,可以带参数,:后面只能有一个表达式
>>> y = lambda x:x**2
>>> y(2)
4
>>>
sorted排序
依据key的值排序,reverse=True反向排序,默认是False
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
>>>
>>> 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)]
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
运行截图
练习材料
瓦尔登湖文本
链接:https://pan.baidu.com/s/1Wt_kEKN36NF716O5XKoisQ
提取码:p9u0