搜索
您的当前位置:首页正文

ex25知识点较多的一课

来源:二三四教育网

如标题一样,这课的知识点确时比较多,先贴上代码

#coding=utf-8

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):
    """Print the last word atfer poping 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 = sort_sentence(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)

从代码来一点点的往下扒

words = stuff.split(' ')
  • python split()方法:通过指定的分隔符对字符中进行切片,split()有两个参数比如,str.split(" ", 2)可以这样理解,把str按空格分隔一次,返回列表格式,代码中没有数字参数,就是分隔到底
sorted(words)
  • sorted()方法有两种用法
x = [3,2,5,4]
x.sort()
x = [3,2,5,4]
sorted(x)

后者会生成一个列表副本,前者直接覆盖本来的列表

word = words.pop(0)
  • python pop()方法:从列表中移除并返回最后一个对象,参数可以选择对象的索引,默认是最后一个对象被返回且被删除

  • 补充一个降序排列方法reverse()

这课有意思的地方就是,在python解析器中,以交互的方式和自己写的这个ex25.py交流,需要的就是在交互前先执行import ex25,是不是有点想起了之前引用的模块,暂进可以这么理解,我们都是在引用某个模块中的某种方法或是函数,比如这课的代码,import ex25后就可以调用里面的函数,使用方式是ex25.bread_words()那么,更好玩的是,你可以查看你自己写的代码的帮助文档,在windows powershell键入python -m pydoc ex25
也可以查看ex25里函数的帮助文档,键入pyhton -m pydoc ex25.break_words

0000.png

看看帮助文档中显示的是代码哪部分

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

热门图文

Top