大爽Python入门教程 2-3 字符串,列表,字典
大爽Python入门公开课教案
点击查看教程总目录
除了通用的序列方法,
列表和字符串还有些自己的专属方法。
后面介绍有些是英中文对照介绍(英文来自官方文档),
便于大家更深入的去理解其意思。
灵活的创建
创建空字符串,空列表,空字典的基础写法
# 创建空字符串
s = ''
# 创建空列表
l = []
# 创建空字典
d = {}
使用内建方法来创建空字符串,空列表,空字典
# 创建空字符串
s = str()
# 创建空列表
l = list()
# 创建空字典
d = dict()
字符串,列表,还可以通过转换其他类型数据得到
>>> s1 = str(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.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
。
调用该方法的字符串将作为可迭代对象的元素之间的分隔。
>>> "12301530133".replace("0", " ")
'123 153 133'
>>> "a > b > c".replace(">", "<")
'a < b < c'
>>> "old words, old songs".replace("old", "new")
'new words, new songs'
>>> "math music history ".split()
['math', 'music', 'history']
>>> "li hua,zhang san,li ming".split(",")
['li hua', 'zhang san', 'li ming']
>>> "math music history ".split()
['math', 'music', 'history']
>>> "12:30:05".split(":")
['12', '30', '05']
>>> " ".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(item)
:
Remove the first item from the list whose value is equal to x.
It raises a ValueError if there is no such item.
从列表中删除item
,有多个相同的item
则只删除第一个,没有item
则报错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
原文地址:https://www.cnblogs.com/BigShuang/p/15161470.html
- WordPress获取文章浏览总数
- HDUOJ----Safecracker(1015)
- hduoj---Tempter of the Bone
- nyoj------------找球号(一)
- nyoj------擅长排列的小明
- HDUOJ-------(1211)RSA
- HDUOJ----1301 Jungle Roads
- try语句...
- HDUOJ---1233还是畅通工程
- HDUOJ---1863畅通工程
- HDUOJ---1879 继续畅通工程
- MySQL命令行工具:percona-toolkit安装使用初探
- 解决Nginx配置http2不生效,谷歌浏览器仍然采用http1.1协议问题
- 海量数据切分抽取的实践场景(r11笔记第43天)
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 0791-5.13.1-Hive视图执行show create table被截断异常分析
- SpringBoot系列之IDEA项目中设置热部署教程
- [教程] 创建第一条 Substrate 链
- SpringBoot系列之actuator监控管理极速入门与实践
- 如何查看JVM运行的堆内存情况
- axios不支持finally的解决办法
- 【机器学习基础】关于Scikit-Learn,你不一定知道的10件事
- Java高级技术梳理
- IDEA使用指北
- 工作记录二: 记录一次简单的SQL优化过程
- Elastic Search
- [数据结构与算法] 图结构
- [数据结构与算法]赫夫曼树与赫夫曼编码
- [数据结构与算法] 查找算法
- Kafka——分布式的消息队列