第4章 Python 数据结构

本章知识点:

1、元组、列表和字典的创建和使用;

2、元组的遍历; 5、字典特性;

3、元组和列表的"解包"操作;

4、列表的排序、查找和反转;

6、序列的含义;

4.1 元组的结构

4.1.1 元组的创

1 tuple = ("apple")
2 print (tuple[0])
3 print (type(tuple))
4 # 输出:a
5 #      <class 'str'>
View Code
1 tuple = ("apple",)
2 print (tuple[0])
3 print (type(tuple))
4 # 输出:apple
5 #      <class 'tuple'>
View Code

4.1.2 元组的访问

1 tuple = ("apple", "banana", "grape", "orange")
2 print (tuple[1])
View Code
 1 print (tuple[-1])
 2 print (tuple[-2])
 3 tuple2 = tuple[1:3]
 4 tuple3 = tuple[0:-2]
 5 tuple4 = tuple[2:-2]
 6 print (tuple2)
 7 print (tuple3)
 8 print (tuple4)
 9 # 输出:orange
10 #     grape
11 #     ('banana', 'grape')
12 #     ('apple', 'banana')
13 #     ()
View Code
 1 fruit1 = ("apple", "banana")
 2 fruit2 = ("grape", "orange")
 3 tuple = (fruit1, fruit2)
 4 print (tuple)
 5 print ("tuple[0][1] =", tuple[0][1])
 6 print ("tuple[1][1] =", tuple[1][1])
 7 print ("tuple[1][1] =", tuple[1][2])
 8 # 输出:(('apple', 'banana'), ('grape', 'orange'))
 9     # tuple[0][1] = banana
10     # tuple[1][1] = orange
11     # IndexError: tuple index out of range
View Code
1 # 打包
2 tuple = ("apple", "banana", "grape", "orange")
3 # 解包
4 a, b, c, d = tuple
5 print (a, b, c , d)
6 # 输出:apple banana grape orange
View Code

4.1.3 元组的遍历

 1 tuple = (("apple", "banana"), ("grape", "orange"),("watermelon",),("grapefruit",))
 2 for i in range(len(tuple)):
 3     print ("tuple[%d]:" % i," ",)
 4     for j in range(len(tuple[i])):
 5         print (tuple[i][j]," ",)
 6     print ()
 7 # 输出:tuple[0]:
 8     # apple
 9     # banana
10     #
11     # tuple[1]:
12     # grape
13     # orange
14     #
15     # tuple[2]:
16     # watermelon
17     #
18     # tuple[3]:
19     # grapefruit
20 for i in tuple:
21     for j in i:
22         print (j)
23 # 输出:apple
24     # banana
25     # grape
26     # orange
27     # watermelon
28     # grapefruit
View Code

4.2 列表结构

4.2.1 列表的创建

 1 list =[]
 2 print (list)
 3 # # 输出:[]
 4 list = ["apple", "banana", "grape", "orange"]
 5 print (list)
 6 print (list[2])
 7 # # 输出:['apple', 'banana', 'grape', 'orange']
 8 #        grape
 9 ## 添加
10 list.append("watermelon")
11 print (list)
12 # 输出:['apple', 'banana', 'grape', 'orange', 'watermelon']
13 ## 插入
14 list.insert(1, "grapefruit")
15 print (list)
16 # 输出:['apple', 'grapefruit', 'banana', 'grape', 'orange', 'watermelon']
17 ## 删除
18 list.remove("grape")
19 # list.remove("a")
20 print (list)
21 # 输出:['apple', 'grapefruit', 'banana', 'orange', 'watermelon']
22 #      ValueError: list.remove(x): x not in list
23 print (list.pop())
24 print (list)
25 # 输出:watermelon
26 #        ['apple', 'grapefruit', 'banana', 'orange']
View Code

4.2.2 列表的使用

 1 list = ["apple", "banana", "grape", "orange"]
 2 print (list[-2])
 3 print (list[1:3])
 4 print (list[-3:-1])
 5 list = [["apple", "banana"], ["grape", "orange"], ["watermelon"], ["grapefruit"]]
 6 for i in range(len(list)):
 7     print ("list[%d]:" % i, "",)
 8     for j in range(len(list[i])):
 9         print (list[i][j], "",)
10     print ()
11 # 输出:grape
12 # ['banana', 'grape']
13 # ['banana', 'grape']
14 # list[0]: 
15 # apple 
16 # banana 
17 # 
18 # list[1]: 
19 # grape 
20 # orange 
21 # 
22 # list[2]: 
23 # watermelon 
24 # 
25 # list[3]: 
26 # grapefruit 
View Code
 1 list1 = ["apple", "banana"]
 2 list2 = ["grape", "orange"]
 3 list1.extend(list2)
 4 print (list1)
 5 list3 = ["watermelon"]
 6 list1 = list1 + list3
 7 print (list1)
 8 list1 += ["grapefruit"]
 9 print (list1)
10 list1 = ["apple", "banana"] * 2
11 print (list1)
12 # 输出:['apple', 'banana', 'grape', 'orange']
13 # ['apple', 'banana', 'grape', 'orange', 'watermelon']
14 # ['apple', 'banana', 'grape', 'orange', 'watermelon', 'grapefruit']
15 # ['apple', 'banana', 'apple', 'banana']
View Code

4.2.3 列表的查找、排序、反转

1 list = ["apple", "banana", "grape", "orange"]
2 print (list.index("grape"))  # 查找
3 print (list.index("orange"))  # 查找
4 print ("orange" in list)  # 查找
5 # 输出:2
6 # 3
7 # True
View Code
1 list = ["apple", "banana", "grape", "orange"]
2 list.sort()  # 排序
3 print ("Sorted list:", list)
4 list.reverse()  # 反转
5 print ("Reverse:", list)
6 # 输出:Sorted list: ['apple', 'banana', 'grape', 'orange']
7 # Reverse: ['orange', 'grape', 'banana', 'apple']
View Code

4.2.4 列表实现堆栈和列队

1 list = ["apple", "banana", "grape"]
2 list.append("orange")  # 添加
3 print (list)
4 print ("弹出的元素:", list.pop())  # 删除
5 print (list)
6 # 输出:['apple', 'banana', 'grape', 'orange']
7 # 弹出的元素: orange
8 # ['apple', 'banana', 'grape']
View Code
1     ## 列对
2 list = ["apple", "banana", "grape"]
3 list.append("orange")  # 添加
4 print (list)
5 print ("弹出的元素:", list.pop(0))  # 删除(0)
6 print (list)
7 # 输出:['apple', 'banana', 'grape', 'orange']
8 # 弹出的元素: apple
9 # ['banana', 'grape', 'orange']
View Code

4.3 字典结构 

4.3.1 字典的创建

 1 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
 2 print (dict)
 3 print (dict["a"])
 4 # 输出:{'a': 'apple', 'b': 'banana', 'c': 'grape', 'd': 'orange'}
 5 # apple
 6 dict = {1:"apple", 2:"banana", 3:"grape", 4:"orange"}
 7 print (dict)
 8 print (dict[3])
 9 # 输出:{1: 'apple', 2: 'banana', 3: 'grape', 4: 'orange'}
10 # grape
11 dict = {"a":"apple", "b":"banana", "A":"grape", "B":"orange"}  # 区分大小写
12 print (dict)
13 print (dict["A"])
14 # 输出:{'a': 'apple', 'b': 'banana', 'A': 'grape', 'B': 'orange'}
15 # grape
View Code

4.3.2 字典的访问

 1    ## 添加、删除、修改
 2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
 3 dict["w"] = "watermelon"  # 添加
 4 del(dict["a"])  # 删除
 5 dict["g"] = "grapefruit"
 6 print (dict.pop("b"))  # 弹出(删除)
 7 print (dict)
 8 dict.clear()  # 清除字典
 9 print (dict)  
10 # 输出:banana
11 # {'c': 'grape', 'd': 'orange', 'w': 'watermelon', 'g': 'grapefruit'}
12 # {}
View Code
1 ## 字典的遍历
2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
3 for k in dict:
4     print ("dict[%s] ="% k,dict[k])
5 # 输出:dict[a] = apple
6 # dict[b] = banana
7 # dict[c] = grape
8 # dict[d] = orange
View Code
1 ## 字典items()的使用
2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
3 print (dict.items())
4 # 输出:dict_items([('a', 'apple'), ('b', 'banana'), ('c', 'grape'), ('d', 'orange')])
View Code
 1 ## 使用字典、列表作为字典的值
 2 dict = {"a":("apple",), "bc":{"b":"banana", "c":"grape"}, "d":["orange","grapefruit"]}
 3 print (dict["a"])
 4 print (dict["a"][0])
 5 print (dict["bc"])
 6 print (dict["bc"]["c"])
 7 print (dict["d"])
 8 print (dict["d"][1])
 9 # 输出:('apple',)
10 # apple
11 # {'b': 'banana', 'c': 'grape'}
12 # grape
13 # ['orange', 'grapefruit']
14 # grapefruit
View Code
1 ## 调用items()实现字典的遍历
2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
3 for (k, v) in dict.items():
4     print ("dict[%s] ="% k, v)
5 # 输出:dict[a] = apple
6 # dict[b] = banana
7 # dict[c] = grape
8 # dict[d] = orange
View Code

 4.3.3 字典的方法

1 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
2 ## 输出key的列表
3 print (dict.keys())
4 ## 输出value的列表
5 print (dict.values())
6 # 输出:dict_keys(['a', 'b', 'c', 'd'])
7 # dict_values(['apple', 'banana', 'grape', 'orange'])
View Code
1 ## get()的等价语句
2 D = {"key1":"value1", "key2":"value2"}
3 if "key1" in D:
4     print (D["key1"])
5 else:
6     print ("None")
View Code
1 ## 字典中元素的获取方法
2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
3 print (dict)
4 print (dict.get("c", "apple"))
5 print (dict.get("e", "banana"))
6 # 输出:{'a': 'apple', 'b': 'banana', 'c': 'grape', 'd': 'orange'}
7 # grape
8 # banana
View Code
1 ## udpate()的等价语句
2 D = {"key1":"value1", "key2":"value2"}
3 E = {"key3":"value3", "key4":"value4"}
4 for k in E:
5     D[k] = E[k]
6 print (D)
7 # 输出:{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
View Code
1 ## 字典E中含有字典D中的key
2 D = {"key1":"value1", "key2":"value2"}
3 E = {"key2":"value3", "key4":"value4"}
4 for k in E:
5     D[k] = E[k]
6 print (D)
7 # 输出:{'key1': 'value1', 'key2': 'value3', 'key4': 'value4'}
View Code
1 ## 字典的更新
2 dict1 = {"a":"apple", "b":"banana", }
3 print (dict)
4 dict2 = {"c":"grape", "d":"orange"}
5 dict1.update(dict2)
6 print (dict1)
7 # 输出:<class 'dict'>
8 # {'a': 'apple', 'b': 'banana', 'c': 'grape', 'd': 'orange'}
View Code
1 dict = {}
2 dict.setdefault("a")
3 print (dict)
4 dict["a"] = "apple"
5 dict.setdefault("a","None")
6 print (dict)
7 # 输出:{'a': None}
8 # {'a': 'apple'}
View Code

4.3.4 字典的排序、复制

 1 ## 调用sorted()排序
 2 dict = {"a":"apple", "b":"banana", "c":"grape", "d":"orange"}
 3 print (dict)
 4 ## 按照key排序
 5 print (sorted(dict.items(), key = lambda d:d[0]))
 6 ## 按照value排序
 7 print (sorted(dict.items(), key = lambda d:d[1]))
 8 # 输出:{'a': 'apple', 'b': 'banana', 'c': 'grape', 'd': 'orange'}
 9 # [('a', 'apple'), ('b', 'banana'), ('c', 'grape'), ('d', 'orange')]
10 # [('a', 'apple'), ('b', 'banana'), ('c', 'grape'), ('d', 'orange')]
View Code
 1 ## 字典的深拷贝
 2 import copy
 3 dict1 = {"a":"apple", "b":{"c":"grape", "d":"orange"}}
 4 dict2 = copy.deepcopy(dict1)  # 深拷贝
 5 dict3 = copy.copy(dict1)  # 浅拷贝
 6 dict2["b"]["c"] = "orange"
 7 print (dict1)
 8 dict3["b"]["c"] = "orange"
 9 print (dict1)
10 # 输出:{'a': 'apple', 'b': {'c': 'grape', 'd': 'orange'}}
11 # {'a': 'apple', 'b': {'c': 'orange', 'd': 'orange'}}
View Code
 1 import sys
 2 print (sys.modules.keys())
 3 print (sys.modules.values())
 4 print (sys.modules("os"))
 5 # 输出:dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', 
 6 # '_warnings', '_thread', '_weakref', '_frozen_importlib_external',
 7 #  '_io', 'marshal', 'nt', 'winreg', 'zipimport', 'encodings', 'codecs',
 8 #  '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 
 9 # 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 
10 # 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', 
11 # '_sitebuiltins', 'sysconfig', '_bootlocale', '_locale', 'encodings.gbk', 
12 # '_codecs_cn', '_multibytecodec', 'types', 'functools', '_functools', 
13 # 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 
14 # 'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 
15 # 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 
16 # 'warnings', 'importlib.util', 'importlib.abc', 'importlib.machinery', 
17 # 'contextlib', 'mpl_toolkits', 'sphinxcontrib', 'sitecustomize', 'copy', 'copyreg'])
18 # dict_values([<module 'builtins' (built-in)>, <module 'sys' (built-in)>,
19 #  <module 'importlib._bootstrap' (frozen)>, <module '_imp' (built-in)>, 
20 # <module '_warnings' (built-in)>, <module '_thread' (built-in)>, 
21 # <module '_weakref' (built-in)>, <module 'importlib._bootstrap_external' (frozen)>, 
22 # <module 'io' (built-in)>, <module 'marshal' (built-in)>, <module 'nt' (built-in)>, 
23 # <module 'winreg' (built-in)>, <module 'zipimport' (built-in)>, 
24 # <module 'encodings' from 'F:\\Anaconda3\\lib\\encodings\\__init__.py'>, 
25 # <module 'codecs' from 'F:\\Anaconda3\\lib\\codecs.py'>, <module '_codecs' (built-in)>,
26 #  <module 'encodings.aliases' from 'F:\\Anaconda3\\lib\\encodings\\aliases.py'>, 
27 # <module 'encodings.utf_8' from 'F:\\Anaconda3\\lib\\encodings\\utf_8.py'>, 
28 # <module '_signal' (built-in)>, 
29 # <module '__main__' from 'D:/Python/零基础学 python/第4章 Python 数据结构/内容.py'>, 
30 # <module 'encodings.latin_1' from 'F:\\Anaconda3\\lib\\encodings\\latin_1.py'>,
31 #  <module 'io' from 'F:\\Anaconda3\\lib\\io.py'>, 
32 # <module 'abc' from 'F:\\Anaconda3\\lib\\abc.py'>, 
33 # <module '_weakrefset' from 'F:\\Anaconda3\\lib\\_weakrefset.py'>,
34 #  <module 'site' from 'F:\\Anaconda3\\lib\\site.py'>, 
35 # <module 'os' from 'F:\\Anaconda3\\lib\\os.py'>, 
36 # <module 'errno' (built-in)>, <module 'stat' from 'F:\\Anaconda3\\lib\\stat.py'>, 
37 # <module '_stat' (built-in)>, <module 'ntpath' from 'F:\\Anaconda3\\lib\\ntpath.py'>, 
38 # <module 'genericpath' from 'F:\\Anaconda3\\lib\\genericpath.py'>,
39 #  <module 'ntpath' from 'F:\\Anaconda3\\lib\\ntpath.py'>, 
40 # <module '_collections_abc' from 'F:\\Anaconda3\\lib\\_collections_abc.py'>, 
41 # <module '_sitebuiltins' from 'F:\\Anaconda3\\lib\\_sitebuiltins.py'>, 
42 # <module 'sysconfig' from 'F:\\Anaconda3\\lib\\sysconfig.py'>, 
43 # <module '_bootlocale' from 'F:\\Anaconda3\\lib\\_bootlocale.py'>, 
44 # <module '_locale' (built-in)>, 
45 # <module 'encodings.gbk' from 'F:\\Anaconda3\\lib\\encodings\\gbk.py'>, 
46 # <module '_codecs_cn' (built-in)>, <module '_multibytecodec' (built-in)>, 
47 # <module 'types' from 'F:\\Anaconda3\\lib\\types.py'>, 
48 # <module 'functools' from 'F:\\Anaconda3\\lib\\functools.py'>, 
49 # <module '_functools' (built-in)>, 
50 # <module 'collections' from 'F:\\Anaconda3\\lib\\collections\\__init__.py'>, 
51 # <module 'operator' from 'F:\\Anaconda3\\lib\\operator.py'>, 
52 # <module '_operator' (built-in)>, <module 'keyword' from 'F:\\Anaconda3\\lib\\keyword.py'>, 
53 # <module 'heapq' from 'F:\\Anaconda3\\lib\\heapq.py'>, 
54 # <module '_heapq' (built-in)>, <module 'itertools' (built-in)>, 
55 # <module 'reprlib' from 'F:\\Anaconda3\\lib\\reprlib.py'>, 
56 # <module '_collections' (built-in)>, <module 'weakref' from 'F:\\Anaconda3\\lib\\weakref.py'>, 
57 # <module 'collections.abc' from 'F:\\Anaconda3\\lib\\collections\\abc.py'>, 
58 # <module 'importlib' from 'F:\\Anaconda3\\lib\\importlib\\__init__.py'>, 
59 # <module 'importlib._bootstrap' (frozen)>, <module 'importlib._bootstrap_external' (frozen)>,
60 #  <module 'warnings' from 'F:\\Anaconda3\\lib\\warnings.py'>, 
61 # <module 'importlib.util' from 'F:\\Anaconda3\\lib\\importlib\\util.py'>,
62 #  <module 'importlib.abc' from 'F:\\Anaconda3\\lib\\importlib\\abc.py'>, 
63 # <module 'importlib.machinery' from 'F:\\Anaconda3\\lib\\importlib\\machinery.py'>, 
64 # <module 'contextlib' from 'F:\\Anaconda3\\lib\\contextlib.py'>,
65 #  <module 'mpl_toolkits' (namespace)>, 
66 # <module 'sphinxcontrib' from 'F:\\Anaconda3\\lib\\site-packages\\sphinxcontrib\\__init__.py'>,
67 #  <module 'sitecustomize' from 'C:\\PyCharm 2017.3.3\\helpers\\pycharm_matplotlib_backend\\sitecustomize.py'>, 
68 # <module 'copy' from 'F:\\Anaconda3\\lib\\copy.py'>, <module 'copyreg' from 'F:\\Anaconda3\\lib\\copyreg.py'>])
69 # TypeError: 'dict' object is not callable
View Code

 

1 import sys
2 d = sys.modules.copy()
3 import copy, string
4 print (zip(set(sys.modules) - set(d)))
5 # 输出:<zip object at 0x00000249FDEAB108>
View Code

4.4 序列

 1 ## 索引操作
 2 tuple = ("apple", "banana", "grape", "orange")
 3 list = ["apple", "banana", "grape", "orange"]
 4 str = "apple"
 5 print (tuple[0])
 6 print (tuple[-1])
 7 print (list[0])
 8 print (list[-1])
 9 print (str[0])
10 print (str[-1])
11 # 输出:apple
12 # orange
13 # apple
14 # orange
15 # a
16 # e
View Code
 1 ## 切片操作
 2 tuple = ("apple", "banana", "grape", "orange")
 3 list = ["apple", "banana", "grape", "orange"]
 4 str = "apple"
 5 print (tuple[:3])
 6 print (tuple[3:])
 7 print (tuple[1:-1])
 8 print (tuple[:])
 9 print (list[:3])
10 print (list[3:])
11 print (list[1:-1])
12 print (list[:])
13 print (str[:3])
14 print (str[3:])
15 print (str[1:-1])
16 print (str[:])
17 #输出:('apple', 'banana', 'grape')
18 # ('orange',)
19 # ('banana', 'grape')
20 # ('apple', 'banana', 'grape', 'orange')
21 # ['apple', 'banana', 'grape']
22 # ['orange']
23 # ['banana', 'grape']
24 # ['apple', 'banana', 'grape', 'orange']
25 # app
26 # le
27 # ppl
28 # apple
View Code


posted @ 2018-12-23 11:59  无声胜有声  阅读(174)  评论(0)    收藏  举报