From 148dfcc264ef295bdf44623e431d9713eb8dd8e5 Mon Sep 17 00:00:00 2001 From: Hui Lan Date: Thu, 1 Aug 2019 00:10:23 +0800 Subject: =?UTF-8?q?LectureNotesOnPython.rst:=20=E5=9C=A8=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E9=82=A3=E8=8A=82=E5=A2=9E=E5=8A=A0=E4=BA=86=E5=88=9D=E5=AD=A6?= =?UTF-8?q?=E8=80=85=E4=BC=9A=E9=9D=A2=E5=AF=B9=E7=9A=84=E5=9B=B0=E9=9A=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 并且加了两个练习题。 --- LectureNotesOnPython.rst | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'LectureNotesOnPython.rst') diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst index 5bc2d63..6b59791 100644 --- a/LectureNotesOnPython.rst +++ b/LectureNotesOnPython.rst @@ -578,6 +578,28 @@ def,函数名,参数列表: +初学者面对函数时, 往往会卡住。 在开始函数体时, 往往会忘记缩进。 + +比如将一段代码移植到函数时, 往往会手足无措。 原因, 经验不够。 + +**练习** 下面的代码可以统计字符串中各个词出现的次数。 将这个代码片段转换成函数 freq(s), 函数返回一个列表, 列表中每个元素是元组, (word, frequency), word代表词, frequency代表该词出现的次数。 + + +.. code:: python + + + fruit = 'Apple BANANA apple' + fruit = fruit.lower() + flst = fruit.split() + for f in set(flst): + n = flst.count(f) + print('%s has appeared %d times' % (f, n)) + + +**练习** 重写上面的freq函数, 使得返回的列表是按照frequency从大到小排好序的, 如 [('apple', 2), ('banana', 1)]。 apple在banana之前, 因为apple出现的次数更多。 + + + Python的关键词 -------------------------------- -- cgit v1.2.1