大爽Python入门公开课教案

点击查看教程总目录

除了通用的序列方法,

列表和字符串还有些自己的专属方法。

后面介绍有些是英中文对照介绍(英文来自官方文档),

便于大家更深入的去理解其意思。

灵活的创建

创建空字符串,空列表,空字典的基础写法

# 创建空字符串
s = ''
# 创建空列表
l = []
# 创建空字典
d = {}

使用内建方法来创建空字符串,空列表,空字典

# 创建空字符串
s = str()
# 创建空列表
l = list()
# 创建空字典
d = dict()

字符串,列表,还可以通过转换其他类型数据得到

>>> s1 = str(1)
>>> s1
'1'
>>> s2 = str((1,2,3))
>>> s2
'(1, 2, 3)'
>>> s3 = str(["a", "b"])
>>> s3
"['a', 'b']"
>>> l1 = list("abcde")
>>> l1
['a', 'b', 'c', 'd', 'e']
>>> l2 = list((1,2,3))
>>> l2
[1, 2, 3]

注:字典数据结构比较特殊,匹配的可以用于转换的数据类型,

我好像还没看到过。

字符串方法

字符串的方法繁多,

这里只介绍最基础常用且适合现阶段的。

未来会再拓展补充

  • str.find(sub)

    Return the lowest index in the string where substring sub is found.

    Return -1 if sub is not found.

    查找子字符substr中首次出现的位置(索引),返回该索引。

    (如果该值出现了多次,会得到第一个对应的索引)

    如果没出现过,会返回-1。

  • str.replace(old, new):

    Return a copy of the string with all occurrences of substring old replaced by new.

    返回字符串的副本,其中出现的所有子字符串old都将被替换为new

  • str.split(sep=None):

    Return a list of the words in the string, using sep as the delimiter string.

    返回一个由字符串内单词组成的列表,使用sep作为分隔字符串。

    (如果sep未指定或为None,则会应用另一种拆分算法:连续的空格会被视为单个分隔符。如果字符串包含前缀或后缀空格的话,返回结果将不包含开头或末尾的空字符串。)

  • str.join(iterable):

    Return a string which is the concatenation of the strings in iterable.

    A TypeError will be raised if there are any non-string values in iterable.

    The separator between elements is the string providing this method.

    返回一个字符串,该字符串为用原字符串拼接(分隔)可迭代对象iterable的项得到。

    (iterable,可迭代对象,序列属于可迭代对象)

    如果iterable中存在任何非字符串值,则会报错TypeError

    调用该方法的字符串将作为可迭代对象的元素之间的分隔。

>>> s = "abc cba"
>>> s.find("a")
0
>>> s.find("b")
1
>>> s.find("d")
-1
>>> "12301530133".replace("0", " ")
'123 153 133'
>>> "a > b > c".replace(">", "<")
'a < b < c'
>>> "old words, old songs".replace("old", "new")
'new words, new songs'
>>> "li hua,zhang san,li ming".split(",")
['li hua', 'zhang san', 'li ming']
>>> "12:30:05".split(":")
['12', '30', '05']
>>> "a-b-c-".split("-")
['a', 'b', 'c', '']
>>> "math music history ".split()
['math', 'music', 'history']
>>> "math music history ".split(" ")
['math', 'music', '', 'history', '']
>>> " ".join(['math', 'music', 'history'])
'math music history'
>>> "-".join(['2020', '1', '1'])
'2020-1-1'
>>> "-".join("abcde")
'a-b-c-d-e'

列表方法

超常用

list.append(item):

Add an item to the end of the list.

在列表的末尾添加item

示例

>>> courses = []
>>> courses.append("Math")
>>> courses.append("English")
>>> courses
['Math', 'English']
>>> courses.append("Music")
>>> courses
['Math', 'English', 'Music']

这个超常用的需要专门记一下。

下面常用的看一下就好,有个概念就行。

后面用的时候会查就行。

有的用的多了,自然也就记住了。

常用

  • list.insert(index, item):

    Insert an item at a given position.

    在给定位置插入itemindex是位置的索引,。
  • list.remove(x):

    Remove the first item from the list whose value is equal to x.

    It raises a ValueError if there is no such item.

    从列表中删除值等于x的项,有多个相同的x则只删除第一个,没有x则报错ValueError
  • list.pop(index=-1):

    Remove the item at the given position in the list, and return it.

    If no index is specified, a.pop() removes and returns the last item in the list.

    删除列表中给定位置的项,index为该位置的索引,然后将其值返回。

    如果未指定索引,将删除并返回列表中的最后一项。

使用示例

>>> nums = [9, 12, 10, 12, 15]
>>> nums.insert(0, 20)
>>> nums
[20, 9, 12, 10, 12, 15]
>>> nums.insert(2, 15)
>>> nums
[20, 9, 15, 12, 10, 12, 15]
>>> nums.remove(20)
>>> nums
[9, 15, 12, 10, 12, 15]
>>> nums.remove(15)
>>> nums
[9, 12, 10, 12, 15]
>>> nums.pop()
15
>>> nums
[9, 12, 10, 12]
>>> nums.pop(2)
10
>>> nums
[9, 12, 12]

更多方法(感兴趣可以拓展):

more-on-lists

字典

相似与不同

字典不同于序列。

字典是一个又一个键值对key:value组成。

虽然同样用方括号,

dict[key]的方括号中的是键key

而不是序列的索引index

字典不支持序列的切片操作的。

dict[key]能得到key对应的value

如果字典中不存在key这个键,则会报错KeyError

修改某个键值对的值,可以使用dict[key]=new_value

无法直接修改键值对的键(只能删去这个键值对,再添加新的)

字典也可以使用len(dict)函数得到其键值对的个数。

常用方法

  • dict.get(key, default):

    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    如果字典中存在key,则返回key对应的值,否则返回default

    如果default未给出则默认为None,因而此方法绝不会引发KeyError

  • dict.keys(key, default):

    Return a new view of the dictionary’s keys.

    返回由字典键组成的一个新的view对象。

  • dict.items(key, default):

    Return a new view of the dictionary’s items ((key, value) pairs).

    返回由字典项(键值对,元组格式)组成的一个新的view对象。

下面介绍两个相关的但不太常用的方法

  • dict.values(key, default):

    Return a new view of the dictionary’s values.

    返回由字典值组成的一个新的view对象。
  • dict.pop(key, default):

    If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

    如果key存在于字典中,则将其移除并返回其值,否则返回 default。如果default未给出且key不存在于字典中,则会引发KeyError

这两者不太常用,大多数练习题或实践很少光取字典的值,

也很少删除字典的键值对。

dict.keys(), dict.values()dict.items()方法都会返回view对象。

They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

该对象提供字典条目的一个动态视图,这意味着当字典改变时,视图对象也会相应改变。

目前对该对象只需要了解以下三点即可

  • 这个对象可以迭代(即可以使用for循环遍历)。
  • 这个对象是动态的,当字典改变时,其内部会跟着边。
  • 这个对象不支持序列的索引操作,想要用索引操作可以用list()方法将其转换成列表。转换后的列表不会跟随字典变化。

使用示例

>>> ages = {"A": 18, "B": 20, "C": 26}
>>> len(ages)
3
>>> ages["A"]
18
>>> ages["D"]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ages["D"]
KeyError: 'D'
>>> ages.get("A")
18
>>> ages.get("D")
>>> keys = ages.keys()
>>> keys
dict_keys(['A', 'B', 'C'])
>>> items = ages.items()
>>> items
dict_items([('A', 18), ('B', 20), ('C', 26)])
>>> values = ages.values()
>>> values
dict_values([18, 20, 26])
>>> ages["E"] = 22
>>> len(ages)
4
>>> ages
{'A': 18, 'B': 20, 'C': 26, 'E': 22}
>>> keys
dict_keys(['A', 'B', 'C', 'E'])
>>> values
dict_values([18, 20, 26, 22])
>>> items
dict_items([('A', 18), ('B', 20), ('C', 26), ('E', 22)])
>>> ages.pop("B")
20
>>> ages
{'A': 18, 'C': 26, 'E': 22}
>>> keys
dict_keys(['A', 'C', 'E'])
>>> values
dict_values([18, 26, 22])
>>> items
dict_items([('A', 18), ('C', 26), ('E', 22)])
>>> for key in keys:
... print(key, ages[key])
...
A 18
C 26
E 22
>>> for key, value in items:
... print(key, value)
...
A 18
C 26
E 22

遍历(循环)

遍历(Traversal),简单来讲,就是沿着某种顺序(一般为线性顺序),

依次对容器中每个项做一次访问。

遍历列表

for item in a_list: 遍历的是列表里面的所有的项

>>> a_list = ["language", "math", "english"]
>>> for item in a_list:
... print(item)
...
language
math
english

直接遍历的局限性:

对于列表而言,直接遍历只得到了项的值,

并不能直接得到项的索引,如果刚好有使用索引的需要的话,

往往需要去计算其索引。

>>> i = 0
>>> for item in a_list:
... print(i, item)
... i += 1
...
0 language
1 math
2 english

比起直接计算,一般使用range+len方法

来遍历列表所有项的索引,然后获取对应的值。

>>> for i in range(len(a_list)):
... item = a_list[i]
... print(i, item)
...
0 language
1 math
2 english

遍历字典

for key in a_dict: 遍历的是字典里面的所有的键

>>> a_dict = {"a": 12, "b": 13, "c": 11}
... for key in a_dict:
... print(key)
...
a
b
c

对于字典而言,有时候只需要遍历所有的键,使用上面的方法就可以,

但也有时候,需要遍历所有的键值对,

对于字典而言,获取对应的值比列表记录索引要简单,只用dict[key]就好。

>>> for key in a_dict:
... value = a_dict[key]
... print(key, value)
...
a 12
b 13
c 11

不过实现这样的便利,不少人更喜欢使用dict.items()方法

(其实前者也已经很简单了)。

>>> for key, value in a_dict.items():
... print(key, value)
...
a 12
b 13
c 11

大爽Python入门教程 2-3 字符串,列表,字典的更多相关文章

  1. 大爽Python入门教程 2-2 序列: 字符串、元组与列表

    大爽Python入门公开课教案 点击查看教程总目录 序列 序列(sequence): 顾名思义,有序的排列. 有序排列的一串数据. 一种容器,容器内成员有序排列. python的字符串str,元组tu ...

  2. 大爽Python入门教程 1-2 数与字符串

    大爽Python入门公开课教案 点击查看教程总目录 1 整数与浮点数 整数大家都知道,比如1, 2, 10, 123, 都是整数int. 浮点数是什么呢? 上一节的除法运算,不知道有没有人注意到,其结 ...

  3. 大爽Python入门教程 3-3 循环:`for`、`while`

    大爽Python入门公开课教案 点击查看教程总目录 for循环 可迭代对象iterable 不同于其他语言. python的for循环只能用于遍历 可迭代对象iterable 的项. 即只支持以下语法 ...

  4. 大爽Python入门教程 3-5 习题

    大爽Python入门公开课教案 点击查看教程总目录 1 求平方和 使用循环,计算列表所有项的平方和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, ...

  5. 大爽Python入门教程 3-6 答案

    大爽Python入门公开课教案 点击查看教程总目录 1 求平方和 使用循环,计算列表所有项的平方和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, ...

  6. 大爽Python入门教程 3-1 布尔值: True, False

    大爽Python入门公开课教案 点击查看教程总目录 1 布尔值介绍 从判断说起 回顾第一章介绍的简单的判断 >>> x = 10 >>> if x > 5: ...

  7. 大爽Python入门教程 2-4 练习

    大爽Python入门公开课教案 点击查看教程总目录 方位输出 第一章有一个思考题,方位变换: 小明同学站在平原上,面朝北方,向左转51次之后(每次只转90度), 小明面朝哪里?小明转过了多少圈? (3 ...

  8. 大爽Python入门教程 2-1 认识容器

    大爽Python入门公开课教案 点击查看教程总目录 1 什么是容器 先思考这样一个场景: 有五个学生,姓名分别为: Alan, Bruce, Carlos, David, Emma. 需要给他们都打一 ...

  9. 大爽Python入门教程 3-4 实践例题

    大爽Python入门公开课教案 点击查看教程总目录 1. 求和 使用循环,计算列表所有项的和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11 ...

随机推荐

  1. Winform 实现图片轮播(解决Image.FromFile内存不足)

    前言 最近项目中需要在winform中做一个类似于网页那种轮播的效果,这里做下记录. 实现 整体的实现思路如下: 读取图片文件夹. 建立一个集合存储Image对象. 定时器定时更换PictrueBox ...

  2. 分组密码(五)AES算法② — 密码学复习(八)

    在上一篇简单复习了AES的历史时间节点.产生背景.与DES的对比.算法框图(粗略)以及一些数学基础,如果不记得的话点击这里回顾.下面将介绍AES算法的细节. 下面给出AES算法的流程,图片来源:密码算 ...

  3. 启用 Spring-Cloud-OpenFeign 配置可刷新,项目无法启动,我 TM 人傻了(上)

    本篇文章涉及底层设计以及原理,以及问题定位,比较深入,篇幅较长,所以拆分成上下两篇: 上:问题简单描述以及 Spring Cloud RefreshScope 的原理 下:当前 spring-clou ...

  4. yolov5实战之二维码检测

    目录 1.前沿 2.二维码数据 3.训练配置 3.1数据集设置 3.2训练参数的配置 3.3网络结构设置 3.4训练 3.5结果示例 附录:数据集下载 1.前沿 之前总结过yolov5来做皮卡丘的检测 ...

  5. HTTP基础系列之:一文搞懂URL

    一般我们日常在上网的时候,会在浏览器的地址栏里输入一个网站的 "网址",点击下回车,就会跳到你想去的网站,就类似这样 但其实,叫做 "网址" 并不是特别的准确, ...

  6. Java(11)方法详细介绍

    作者:季沐测试笔记 原文地址:https://www.cnblogs.com/testero/p/15201577.html 博客主页:https://www.cnblogs.com/testero ...

  7. 【HMS Core 6.0全球上线】华为钥匙环服务,打造跨应用跨形态无缝登录体验

    华为钥匙环服务(Keyring),是HMS Core在安全领域开放的全新服务,为全球开发者提供用户认证凭据(以下简称"凭据")本地存储和跨应用.跨形态共享能力,帮助您在安卓应用.快 ...

  8. Scrum Meeting 16

    第16次例会报告 日期:2021年06月11日 会议主要内容概述: 最后一次例会 一.进度情况 我们采用日报的形式记录每个人的具体进度,链接Home · Wiki,如下记录仅为保证公开性: 组员 负责 ...

  9. springboot整合rabbitmq实现生产者消息确认、死信交换器、未路由到队列的消息

    在上篇文章  springboot 整合 rabbitmq 中,我们实现了springboot 和rabbitmq的简单整合,这篇文章主要是对上篇文章功能的增强,主要完成如下功能. 需求: 生产者在启 ...

  10. 表单编辑时el-form的validate方法执行无效,阻塞代码运行 - Element UI踩坑记录

    今天在用element-ui写管理后台需求时,遇到一个奇怪的问题 一个正常带校验的表单,在新增列表数据时表单校验功能正常: 但是在新增之后再去编辑数据时,表单校验却失效了,甚至阻塞了后续的代码执行,控 ...