字典排序 python3_“笨方法”学Python3,习题 25 。

dabd5f8edd112ffbe76529e0d1cc34d3.png

笨方法”学Python3,习题 25:更多更多的练习

1、如何将脚本导入到Python解释器中 ?

2、split 方法、pop 方法、sorted 函数怎么用 ?

一、基础代码

所写的代码(VS code):
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解释器中运行,解释器为下图a的第二个(Python 3.8)
打开解释器,输入import可能会出现图b这一类错误,解决方式如下
复制ex25脚本到python文件夹图c里即可执行
运行结果为图d

75af004ccdf09a5d1357f90d9478757e.png
图a 正中间这个

9852ce73ef08e2b22f7b391a30b259b8.png
图b Python解释器的路径里找不到ex1脚本

ae53080bba67cbecf2276c34a8756120.png
图c 就是和Python文件放在一起

a2accbf897b2225c70fd0e306f37abb0.png
图d 运行结果

二、巩固练习

# 理解脚本的意义需要先了解如下几个函数和方法

split 方法

作用:通过指定的分隔符和切片数目来对字符串进行切片,分隔成“切片数目+1”个字符串,分隔符数目小于要求的切片数目时,以分隔符为准

语法:split(“分隔符”,切片数目),分隔符,默认为所有的空字符,包括空格、换行(n)、制表符(t)等。切片数目默认为 -1, 即分隔所有

例子:

a815dfa320342d56ad9587d5a85a5c5a.png
sorted 函数

作用:对所有可迭代的对象进行排序操作

语法:sorted(iterable, cmp=None, key=None, reverse=False),iterable是可迭代对象,cmp和key先不管。reverse是排序规则,reverse = True是降序 ,False是升序(默认)

例子:

7328e9b5482255cae43af1aa3fe8533d.png
pop 方法

作用:移除列表中的一个元素(默认最后一个元素),并且返回该元素的值;还有针对字典的,这里没涉及

语法:list.pop([index=-1]),参数是要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值

例子:

0908abf5e9df42cc3b35e3640aab1c29.png
1、理解脚本,添加备注

4287709f2c1b874db621e69bd49f5236.png
2、得到文档注释

72492cc640f3ad75b8854680627c8796.png

总结:

1、可以在Python解释器中用import导入脚本

2、可以在Python解释器中用help得到脚本的文档注释

3、from ex25 import * 可以不用重复键入ex25而直接调用里面的函数

4、return会返回给调用本函数的那行代码一个结果,print只是在终端打印输出

^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值