学习内容:
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)
运行结果:
进入Python的方法是直接在控制台输入"Python"→回车
退出Python的方法是直接在控制台输入"quit()"→回车
在Python内调用这个脚本的时候输入脚本时不需要在出入.py,因为本身已经在Python内
里面有出错的地方(懒得再运行一遍了)
知识点:
1.split():
分割字符传,可以在()内指定分隔符。分隔符把字符串分割成若干份,放在list中。需要注意的时分隔符会消失被舍弃掉。
例:split(‘a’, 2)[1]:以a为分隔符,分割2次(2次后后面有a也不再分割)。[1]的意思是取第一个值。2和[1]非必填项。
2.sorted():
Python内置函数,作用是对list进行排序。
①语法(两种都可以):
sorted(interable, cmp = None, key = None,reverse = False)
sorted(interable[, cmp[, key[,reverse]]])
interable:可选迭代对象
cmp:比较函数,具有两个参数,参数的值都是从可迭代对象中取出。
需遵循的原则:大于则返回1,小于则返回-1,等于则返回0.
key:主要用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse:排序规则。reverse为Ture:降序;reverse为False:升序(默认)。
②与list.sort()的区别:
sorted():新建一个新的list;list.sort():对已有的list本身进行操作。
3.pop():
删除字典给定键key所对应的值,反馈值为被删除的值。key必须给出,否则反馈default值。
语法:pop(key[, default])
key:要删除的键值 default:如果没有key,返回default值。
()内没有参数,表示删除list数据组中最后一个元素。
用法:
例:
list1 = ['milk', 'egg', 'bread']
list_pop = list1.pop(0)
print ("Delete the:", list_pop)
print ("The rest of the is:", list1)
结果:
注释:第2行中,pop(0):指删除第一项,从0开始算
第1行中,创建列表用[],用逗号隔开,每个元素用’'或者"“括起来。
若是要提取最后一个字符可以用pop(-1)
4.”#"加注释解释每个函数的作用
# 分割句子
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) # 调用函数break_words,分割句子
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)