大爽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.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'
>>> "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.
    在给定位置插入itemindex是位置的索引,。
  • 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

遍历(循环)

遍历(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
b
c
原文地址:https://www.cnblogs.com/BigShuang/p/15161470.html