大爽Python入门教程 2-3 字符串,列表,字典
大爽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 substringsub
is found.
Return -1 ifsub
is not found.
查找子字符sub
在str
中首次出现的位置(索引),返回该索引。
(如果该值出现了多次,会得到第一个对应的索引)
如果没出现过,会返回-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.
ATypeError
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.
在给定位置插入item
,index
是位置的索引,。list.remove(x)
:
Remove the first item from the list whose value is equal tox
.
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 字符串,列表,字典的更多相关文章
- 大爽Python入门教程 2-2 序列: 字符串、元组与列表
大爽Python入门公开课教案 点击查看教程总目录 序列 序列(sequence): 顾名思义,有序的排列. 有序排列的一串数据. 一种容器,容器内成员有序排列. python的字符串str,元组tu ...
- 大爽Python入门教程 1-2 数与字符串
大爽Python入门公开课教案 点击查看教程总目录 1 整数与浮点数 整数大家都知道,比如1, 2, 10, 123, 都是整数int. 浮点数是什么呢? 上一节的除法运算,不知道有没有人注意到,其结 ...
- 大爽Python入门教程 3-3 循环:`for`、`while`
大爽Python入门公开课教案 点击查看教程总目录 for循环 可迭代对象iterable 不同于其他语言. python的for循环只能用于遍历 可迭代对象iterable 的项. 即只支持以下语法 ...
- 大爽Python入门教程 3-5 习题
大爽Python入门公开课教案 点击查看教程总目录 1 求平方和 使用循环,计算列表所有项的平方和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, ...
- 大爽Python入门教程 3-6 答案
大爽Python入门公开课教案 点击查看教程总目录 1 求平方和 使用循环,计算列表所有项的平方和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, ...
- 大爽Python入门教程 3-1 布尔值: True, False
大爽Python入门公开课教案 点击查看教程总目录 1 布尔值介绍 从判断说起 回顾第一章介绍的简单的判断 >>> x = 10 >>> if x > 5: ...
- 大爽Python入门教程 2-4 练习
大爽Python入门公开课教案 点击查看教程总目录 方位输出 第一章有一个思考题,方位变换: 小明同学站在平原上,面朝北方,向左转51次之后(每次只转90度), 小明面朝哪里?小明转过了多少圈? (3 ...
- 大爽Python入门教程 2-1 认识容器
大爽Python入门公开课教案 点击查看教程总目录 1 什么是容器 先思考这样一个场景: 有五个学生,姓名分别为: Alan, Bruce, Carlos, David, Emma. 需要给他们都打一 ...
- 大爽Python入门教程 3-4 实践例题
大爽Python入门公开课教案 点击查看教程总目录 1. 求和 使用循环,计算列表所有项的和,并输出这个和. 列表示例 lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11 ...
随机推荐
- Spring Security 学习+实践
Spring Security是Spring为解决应用安全所提供的一个全面的安全性解决方案.基于Spring AOP和Servlet过滤器,启动时在Spring上下文中注入了一组安全应用的Bean,并 ...
- 自学 Python,视频教程和代码一看就懂,动手就废,应该这么学
一.代码量太少了,看得多做得少,导致一做就错. 每一个测试工程师必定是在大量的时间和代码中提升的自己,如果你只是看视频的话,那永远都停留在理论上,很多问题是要实践才能发现的 我打个比方你看视频的时 ...
- ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探
前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...
- State Space Model Content
State Space Model 状态空间模型及其卡尔曼滤波技术 混合正态分布下的状态空间模型及其滤波
- NOIP 模拟一 考试总结
序列 考场上信心满满的打了nlogn的做法,我以为我稳了.据考试结束1h时发现看错题目了,打成了不连续的子序列.匆匆改了n2logn的做法.考试结束后,我发现我跪了.原来到终点才会发现我做的和人家不是 ...
- DL4J实战之四:经典卷积实例(GPU版本)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 【c++ Prime 学习笔记】第13章 拷贝控制
定义一个类时,可显式或隐式的指定在此类型对象上拷贝.移动.赋值.销毁时做什么.通过5种成员函数实现拷贝控制操作: 拷贝构造函数:用同类型的另一个对象初始化本对象时做什么(拷贝初始化) 拷贝赋值算符:将 ...
- Scrum Meeting 0602
零.说明 日期:2021-6-2 任务:简要汇报两日内已完成任务,计划后两日完成任务 一.进度情况 组员 负责 两日内已完成的任务 后两日计划完成的任务 困难 qsy PM&前端 完成后端管理 ...
- Prometheus监控Canal
Prometheus监控Canal 一.背景 二.实现步骤 1.修改prometheus.yml配置文件 2.启动prometheus 3.查看prometheus是否成功接入canal 4.cana ...
- 『学了就忘』Linux基础 — 4、VMware安装
目录 1.VMware介绍 2.VMware主要特点 3.VMware建议配置 4.VMware安装 1.VMware介绍 VMware是一个虚拟PC的软件,可以在现有的操作系统上虚拟出一个新的硬件环 ...