言成说 - 数组
type: channel
link: https://www.elecdiy.com/tag/%E6%95%B0%E7%BB%84/
items: ex25 自己写模块，运行其中的函数

ex25 自己写模块，运行其中的函数
type: item
date: 2021-03-28T11:12:14+08:00
description: 学习要点Python split() 通过指定分隔符对字符串进行切片，分割成N个字符串数组words.pop(0) 取数组中首个元素words.pop(-1) 取数组中最后一个元素程序代码def break_words(stuff): """This fuction will break up words for us.""" words = stuff.split(' ') #通过指定分隔符对字符串进行切片，分割成N个字符串数组 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) 模块调用 输出结果 PS D:\lpthw> python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 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. >>> words ['good', 'things', 'come', 'to', 'those', 'who'] >>> ex25.print_first_word(sort_words) All >>> ex25.print_last_word(sort_words) who >>> sort_words ['come', 'good', 'things', 'those', 'to', 'wait.'] >>> sort_words = ex25.sort_sentence(sentence) >>> sort_words ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who'] >>> ex25.print_first_and_last(sentence) All wait. >>> ex…