diff options
author | Hui Lan <lanhui@zjnu.edu.cn> | 2019-08-01 00:10:23 +0800 |
---|---|---|
committer | Hui Lan <lanhui@zjnu.edu.cn> | 2019-08-01 00:10:23 +0800 |
commit | 148dfcc264ef295bdf44623e431d9713eb8dd8e5 (patch) | |
tree | 71a9b11d714be5163e5781209b5bd9b69667f5d5 /LectureNotesOnPython.rst | |
parent | 8eac6475ede2ad5f7c2fb011a59f9581bcdb042d (diff) |
LectureNotesOnPython.rst: 在函数那节增加了初学者会面对的困难
并且加了两个练习题。
Diffstat (limited to 'LectureNotesOnPython.rst')
-rw-r--r-- | LectureNotesOnPython.rst | 22 |
1 files changed, 22 insertions, 0 deletions
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的关键词 -------------------------------- |