大爽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. 分享一下我的Python自学历程,分享下我自己学习方法

    其实关于编程这事儿没有接触的那么早,大一的时候没什么关注点,有一门课是vb,一天天的,就抄抄作业啥的就完事儿了.当时也觉的自己不是学编程的料,想着以后估摸也不会干开发相关的工作. 我的自学历程 阴差阳 ...

  2. JuiceFS v0.17 发布,通过 1270 项 LTP 测试!

    小伙伴们大家好,JuiceFS v0.17 在国庆小长假来临之际如期发布了!这是我们在 2021 年秋季推出的第二个版本,让我们直奔主题,看看都有哪些新变化吧. 本次更新累计 80+ 提交,共有 9 ...

  3. Vulnhub靶机渗透 -- DC6

    信息收集 开启了22ssh和80http端口 ssh可以想到的是爆破,又或者是可以在靶机上找到相应的靶机用户信息进行登录,首先看一下网站信息 结果发现打开ip地址,却显示找不到此网站 但是可以发现地址 ...

  4. spring 创建Bean最全实现方法

    创建bean方式,spring创建bean的方式包含:自动注入方式和人工注入方式.分别为:1)xml 配置化方式  2)@bean注解注入方式3)@Component方式 4)接口注入方式 5)imp ...

  5. 网络基础--简单理解什么是DNS? TCP? UDP? Http? Socket?

    什么是IP 协议?  协议就是为了实现网络通信而创建的一系列规范.  通常我们的网络模型从上到下共分为4层: 应用层, 传输层, 网络层 和数据链路层. IP协议属于网络层协议,它精确定义了网络通信中 ...

  6. golang引用第三方包的报错:no required module provides package [完美解决]

    关于golang第三方包的引用报错:no required module provides package : go.mod file not found in current directory o ...

  7. 力扣 - 剑指 Offer 17. 打印从1到最大的n位数

    题目 剑指 Offer 17. 打印从1到最大的n位数 思路1 如果有n位,那么最大值就是\(10^n-1\),即如果n是2,那么最大就到输出到99 考虑到大数情况,所以使用字符数组 还要把字符数组转 ...

  8. Java(12)方法的重载

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

  9. Pytorch——torch.nn.Sequential()详解

    参考:官方文档    源码 官方文档 nn.Sequential A sequential container. Modules will be added to it in the order th ...

  10. netty系列之:使用netty实现支持http2的服务器

    目录 简介 基本流程 CleartextHttp2ServerUpgradeHandler Http2ConnectionHandler 总结 简介 上一篇文章中,我们提到了如何在netty中配置TL ...