编程语言
首页 > 编程语言> > 第2章 Python序列

第2章 Python序列

作者:互联网

2.1 列表

      

[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
['spam', 2.0, 5, [10, 20]]
[['file1', 200,7], ['file2', 260,9]]
View Code

      

2.1.1 列表创建与删除

>>> a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> a_list = []                                       #创建空列表
View Code
>>> a_list = list((3,5,7,9,11))
>>> a_list
[3, 5, 7, 9, 11]
>>> list(range(1,10,2))
[1, 3, 5, 7, 9]
>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> x = list()                                        #创建空列表
View Code
>>> del a_list
>>> a_list
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a_list
NameError: name 'a_list' is not defined
View Code

2.1.2 列表元素的增加

>>> aList = [3,4,5]
>>> aList = aList + [7]
>>> aList
[3, 4, 5, 7]
View Code
>>> aList.append(9)
>>> aList
[3, 4, 5, 7, 9]
View Code

  所谓 “原地”,是指不改变列表在内存中的首地址。

import time

result = []
start = time.time()
for i in range(10000):
    result = result + [i]
print(len(result), ',', time.time()-start)

result = []
start = time.time()
for i in range(10000):
    result.append(i)
print(len(result), ',', time.time()-start)
View Code
>>> a = [1,2,3]
>>> id(a)                        #返回对象的内存地址
20230752
>>> a = [1,2]
>>> id(a)
20338208
View Code
>>> a = [1,2,4]
>>> b = [1,2,3]
>>> a == b
False
>>> id(a) == id(b)
False
>>> id(a[0]) == id(b[0])
True
>>> a = [1,2,3]
>>> id(a)
25289752
>>> a.append(4)
>>> id(a)
25289752
>>> a.remove(3)
>>> a
[1, 2, 4]
>>> id(a)
25289752
>>> a[0] = 5
>>> a
[5, 2, 4]
>>> id(a)
25289752
View Code
>>> a.extend([7,8,9])
>>> a
[5, 2, 4, 7, 8, 9]
>>> aList.extend([11,13])
>>> aList
[3, 4, 5, 7, 9, 11, 13]
>>> aList.extend((15,17))
>>> aList
[3, 4, 5, 7, 9, 11, 13, 15, 17]
>>> id(a)
25289752
View Code
>>> aList.insert(3, 6)                #在下标为3的位置插入元素6
>>> aList
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
View Code
>>> aList = [3,5,7]
>>> bList = aList
>>> id(aList)
57091464
>>> id(bList)
57091464
>>> aList = aList*3
>>> aList
[3, 5, 7, 3, 5, 7, 3, 5, 7]
>>> bList
[3,5,7]
>>> id(aList)
57092680
>>> id(bList)
57091464
View Code
>>> x = [[None] * 2] * 3
>>> x
[[None, None], [None, None], [None, None]]
>>> x[0][0] = 5
>>> x
[[5, None], [5, None], [5, None]]
>>> x = [[1,2,3]] * 3
>>> x[0][0] = 10
>>> x
[[10, 2, 3], [10, 2, 3], [10, 2, 3]]
View Code

2.1.3 列表元素的删除

>>> a_list = [3,5,7,9,11]
>>> del a_list[1]
>>> a_list
[3, 7, 9, 11]
View Code
>>> a_list = list((3,5,7,9,11))
>>> a_list.pop()
11
>>> a_list
[3, 5, 7, 9]
>>> a_list.pop(1)
5
>>> a_list
[3, 7, 9]
View Code
>>> a_list = [3,5,7,9,7,11]
>>> a_list.remove(7)
>>> a_list
[3, 5, 9, 7, 11]
View Code
>>> x = [1,2,1,2,1,2,1,2,1]
>>> for i in x:
        if i == 1:
          x.remove(i)        
>>> x
[2, 2, 2, 2]
>>> x = [1,2,1,2,1,1,1]
>>> for i in x:
           if i == 1:
        x.remove(i)        
>>> x
[2, 2, 1]
View Code

  正确的代码

>>> x = [1,2,1,2,1,1,1]
>>> for i in x[::]:                             #切片
       if i == 1:
        x.remove(i)

#或者:
>>> x = [1,2,1,2,1,1,1]
>>> for i in range(len(x)-1,-1,-1):
            if x[i]==1:
        del x[i]
View Code

2.1.4 列表元素访问与计数

>>> aList[3]
6
>>> aList[3] = 5.5
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList[15]
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    aList[15]
IndexError: list index out of range
View Code
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList.index(7)
4
>>> aList.index(100)
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    aList.index(100)
ValueError: 100 is not in list
View Code
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList.count(7)
1
>>> aList.count(0)
0
>>> aList.count(8)
0
View Code

2.1.5 成员资格判断

>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> 3 in aList
True
>>> 18 in aList
False
>>> bList = [[1], [2], [3]]
>>> 3 in bList
False
>>> 3 not in bList
True
>>> [3] in bList
True
>>> aList = [3, 5, 7, 9, 11]
>>> bList = ['a', 'b', 'c', 'd']
>>> (3, 'a') in zip(aList, bList)
True
>>> for a, b in zip(aList, bList):
    print(a, b)
View Code

2.1.6 切片操作

>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> aList[::]                                                #返回包含元素的新列表
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> aList[::-1]                                             #逆序的所有元素
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
>>> aList[::2]                                               #偶数位置,隔一个取一个
[3, 5, 7, 11, 15]
>>> aList[1::2]                                             #奇数位置,隔一个取一个
[4, 6, 9, 13, 17]
>>> aList[3::]                                               #从下标3开始的所有元素
[6, 7, 9, 11, 13, 15, 17]
>>> aList[3:6]                                              #下标在[3, 6)之间的所有元素
[6, 7, 9]
>>> aList[0:100:1]                                       #前100个元素,自动截断
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> a[100:]                                                  #下标100之后的所有元素,自动截断
[]
>>> x[100]                                                   #直接使用下标访问会发生越界
IndexError: list index out of range
View Code
>>> aList = [3, 5, 7]
>>> aList[len(aList):] = [9]               #在尾部追加元素
>>> aList
[3, 5, 7, 9]
>>> aList[:3] = [1, 2, 3]                  #替换前3个元素
>>> aList
[1, 2, 3, 9]
>>> aList[:3] = []                         #删除前3个元素
>>> aList
[9]
>>> aList = list(range(10))
>>> aList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> aList[::2] = [0]*5                     #替换偶数位置上的元素
>>> aList
[0, 1, 0, 3, 0, 5, 0, 7, 0, 9]
>>> aList[::2] = [0]*3                     #切片不连续,两个元素个数必须一样多
ValueError: attempt to assign sequence of size 3 to extended slice of size 5
View Code
>>> aList = [3,5,7,9,11]
>>> del aList[:3]                          #删除前3个元素
>>> aList
[9, 11]

>>> aList = [3,5,7,9,11]
>>> del aList[::2]                         #删除偶数位置上的元素
>>> aList
[5, 9]
View Code
>>> aList = [3, 5, 7]
>>> bList = aList              #bList与aList指向同一个内存
>>> bList
[3, 5, 7]
>>> bList[1] = 8                #修改其中一个对象会影响另一个
>>> aList
[3, 8, 7]
>>> aList == bList             #两个列表的元素完全一样
True
>>> aList is bList              #两个列表是同一个对象
True
>>> id(aList)                     #内存地址相同
19061816
>>> id(bList)
19061816
View Code
>>> aList = [3, 5, 7]
>>> bList = aList[::]                 #切片,浅复制
>>> aList == bList                    #两个列表的元素完全一样
True
>>> aList is bList                    #但不是同一个对象
False
>>> id(aList) == id(bList)            #内存地址不一样
False
>>> bList[1] = 8                      #修改其中一个不会影响另一个
>>> bList
[3, 8, 7]
>>> aList
[3, 5, 7]
View Code

2.1.7 列表排序

>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> import random
>>> random.shuffle(aList)
>>> aList
[3, 4, 15, 11, 9, 17, 13, 6, 7, 5]
>>> aList.sort()                                              #默认是升序排序
>>> aList.sort(reverse = True)                       #降序排序
>>> aList
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
>>> aList.sort(key = lambda x:len(str(x)))      #按转换成字符串的长度排序
>>> aList
[9, 7, 6, 5, 4, 3, 17, 15, 13, 11]
View Code
>>> aList
[9, 7, 6, 5, 4, 3, 17, 15, 13, 11]
>>> sorted(aList)                                     #升序排序
[3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> sorted(aList,reverse = True)             #降序排序
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
View Code
>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> aList.reverse()
>>> aList
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
View Code
>>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
>>> newList = reversed(aList)                      #返回reversed对象
>>> list(newList)                                           #把reversed对象转换成列表
[17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
>>> for i in newList:
       print(i, end=' ')                                       #这里没有输出内容
                                                                      #迭代对象已遍历结束
>>> newList = reversed(aList)                      #重新创建reversed对象
>>> for i in newList:
       print(i, end=' ')
17 15 13 11 9 7 6 5 4 3
View Code

2.1.8 用于序列操作的常用内置函数

>>> sum(range(1, 11))               #sum()函数的start参数默认为0
55
>>> sum(range(1, 11), 5)           #指定start参数为5,等价于5+sum(range(1,11))
60
>>> sum([[1, 2], [3], [4]], [])         #这个操作占用空间较大,慎用
[1, 2, 3, 4]
View Code
>>> aList = [1, 2, 3]
>>> bList = [4, 5, 6]
>>> cList = zip(a, b)                               #返回zip对象
>>> cList
<zip object at 0x0000000003728908>
>>> list(cList)                                         #把zip对象转换成列表
[(1, 4), (2, 5), (3, 6)]
View Code
>>> for item in enumerate('abcdef'):
    print(item)
View Code

2.1.9 列表推导式

>>> aList = [x*x for x in range(10)]

  相当于

>>> aList = []
>>> for x in range(10):
        aList.append(x*x)

  也相当于

>>> aList = list(map(lambda x: x*x, range(10)))

  例子:

>>> sum([2**i for i in range(64)])
18446744073709551615
>>> vec = [[1,2,3], [4,5,6], [7,8,9]] 
>>> [num for elem in vec for num in elem] 
[1, 2, 3, 4, 5, 6, 7, 8, 9] 
View Code

  相当于

>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> result = []
>>> for elem in vec:
      for num in elem:
        result.append(num)
>>> result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
View Code

  不使用列表推导式:

>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(vec, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
#或
>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> from itertools import chain
>>> list(chain(*vec))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
View Code
>>> import os
>>> [filename for filename in os.listdir('.') if filename.endswith(('.py', '.pyw'))]
View Code
>>> aList = [-1,-4,6,7.5,-2.3,9,-11]
>>> [i for i in aList if i>0]
[6, 7.5, 9]
View Code

  例子:已知有一个包含一些同学成绩的字典,计算成绩的最高分、最低分、平均分,并查找所有最高分同学。

>>> scores = {"Zhang San": 45, "Li Si": 78, "Wang Wu": 40, "Zhou Liu": 96, "Zhao Qi": 65, "Sun Ba": 90, "Zheng Jiu": 78, "Wu Shi": 99, "Dong Shiyi": 60}
>>> highest = max(scores.values())
>>> lowest = min(scores.values())
>>> average = sum(scores.values())*1.0/len(scores)
>>> highest, lowest, average
99  40  72.33333333333333
>>> highestPerson = [name for name, score in scores.items() if score == highest]
>>> highestPerson
['Wu Shi']
View Code
>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
View Code
>>>matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 
>>> [[row[i] for row in matrix] for i in range(4)] 
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] 
View Code
>>>list(zip(*matrix))                 #序列解包
 [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] 
View Code
>>> def f(v):
    if v%2 == 0:
        v = v**2
    else:
        v = v+1
    return v

>>> [f(v) for v in [2, 3, 4, -1] if v>0]
[4, 4, 16]
>>> [v**2 if v%2 == 0 else v+1 for v in [2, 3, 4, -1] if v>0]
[4, 4, 16]
View Code
>>> with open('C:\\RHDSetup.log', 'r') as fp: 
        print([line for line in fp])
View Code
>>> [p for p in range(2, 100) if 0 not in [p%d for d in range(2, int(p**0.5)+1)]]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
View Code

2.1.10 使用列表实现向量运算

>>> import random
>>> x = [random.randint(1,100) for i in range(10)] #生成随机数
>>> list(map(lambda i: i+5, x))                               #所有元素同时加5
>>> x = [random.randint(1,10) for i in range(10)]
>>> y = [random.randint(1,10) for i in range(10)]
>>> import operator
>>> sum(map(operator.mul, x, y))             #向量内积
>>> sum((i*j for i, j in zip(x, y)))                 #向量内积
>>> list(map(operator.add, x, y))               #两个等长的向量对应元素相加
View Code

2.2 元组

2.2.1 元组创建与删除

>>>a_tuple = ('a', 'b', 'mpilgrim', 'z', 'example')
>>> a_tuple
('a', 'b', 'mpilgrim', 'z', 'example')
>>> a = (3)
>>> a
3
>>> a = (3,)                            #包含一个元素的元组,最后必须多写个逗号
>>> a
(3,)
>>> a = 3,                              #也可以这样创建元组
>>> a
(3,)
>>> x = () #空元组
View Code
>>> tuple('abcdefg')                          #把字符串转换为元组
('a', 'b', 'c', 'd', 'e', 'f', 'g')
>>> aList
[-1, -4, 6, 7.5, -2.3, 9, -11]
>>> tuple(aList)                                #把列表转换为元组
(-1, -4, 6, 7.5, -2.3, 9, -11)
>>> s = tuple()                                   #空元组
>>> s
()
View Code

2.2.2 元组与列表的区别

2.2.2 元组的优点

2.2.3 序列解包

>>> x, y, z = 1, 2, 3                      #多个变量同时赋值
>>> v_tuple = (False, 3.5, 'exp')
>>> (x, y, z) = v_tuple
>>> x, y, z = v_tuple
>>> x, y, z = range(3)                   #可以对range对象进行序列解包
>>> x, y, z = iter([1, 2, 3])             #使用迭代器对象进行序列解包
>>> x, y, z = map(str, range(3))    #使用可迭代的map对象进行序列解包
>>> a, b = b, a                              #交换两个变量的值
>>> x, y, z = sorted([1, 3, 2])         #sorted()函数返回排序后的列表
>>> a, b, c = 'ABC'                        #字符串也支持序列解包
View Code
>>> s = {'a':1, 'b':2, 'c':3}
>>> b, c, d = s.items()
>>> b
('c', 3)
>>> b, c, d = s                         #使用字典时不用太多考虑元素的顺序
>>> b
'c'
>>> b, c, d = s.values()
>>> print(b, c, d)
1 3 2
View Code
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> for k, v in zip(keys, values):
      print((k, v), end=' ')
('a', 1) ('b', 2) ('c', 3) ('d', 4) 
View Code
>>> x = ['a', 'b', 'c']
>>> for i, v in enumerate(x):
      print('The value on position {0} is {1}'.format(i,v))

The value on position 0 is a
The value on position 1 is b
The value on position 2 is c
>>> aList = [1,2,3]
>>> bList = [4,5,6]
>>> cList = [7,8,9]
>>> dList = zip(aList, bList, cList)
>>> for index, value in enumerate(dList):
        print(index, ':', value)

0 : (1, 4, 7)
1 : (2, 5, 8)
2 : (3, 6, 9)
View Code
>>> print(*[1, 2, 3], 4, *(5, 6))
1 2 3 4 5 6
>>> *range(4),4
(0, 1, 2, 3, 4)
>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}
>>> {'x': 1, **{'y': 2}}
{'y': 2, 'x': 1}
View Code

2.2.4 生成器推导式

>>> g = ((i+2)**2 for i in range(10))     #创建生成器对象
>>> g
<generator object <genexpr> at 0x0000000003095200>
>>> tuple(g)                                         #将生成器对象转换为元组
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> list(g)                                             #生成器对象已遍历结束,没有元素了
[] 
>>> g = ((i+2)**2 for i in range(10))      #重新创建生成器对象
>>> g.__next__()                             #使用生成器对象的__next__()方法获取元素
4
>>> g.__next__()                             #获取下一个元素
9
>>> next(g)                                      #使用函数next()获取生成器对象中的元素
16
View Code
>>> g = ((i+2)**2 for i in range(10))     #创建生成器对象
>>> g
<generator object <genexpr> at 0x0000000003095200>
>>> tuple(g)                                         #将生成器对象转换为元组
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> list(g)                                             #生成器对象已遍历结束,没有元素了
[] 
>>> g = ((i+2)**2 for i in range(10))      #重新创建生成器对象
>>> g.__next__()                             #使用生成器对象的__next__()方法获取元素
4
>>> g.__next__()                             #获取下一个元素
9
>>> next(g)                                      #使用函数next()获取生成器对象中的元素
16
View Code
>>> g = ((i+2)**2 for i in range(10))
>>> for item in g:                            #使用循环直接遍历生成器对象中的元素
       print(item, end=' ')
4 9 16 25 36 49 64 81 100 121 
>>> x = filter(None, range(20))       #filter对象也具有类似的特点
>>> 5 in x
True
>>> 2 in x                                        #不可再次访问已访问过的元素
False
>>> x = map(str, range(20))           #map对象也具有类似的特点
>>> '0' in x
True
>>> '0' in x                                       #不可再次访问已访问过的元素
False
View Code

2.3 字典

2.3.1 字典创建与删除

>>> a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
>>> x = {}                     #空字典
>>> x
{}
View Code
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{}
View Code
>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'age': None, 'name': None, 'sex': None}
View Code

2.3.2 字典元素的读取

>>> aDict = {'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
'Dong'
>>> aDict['tel']                                 #键不存在,抛出异常
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    aDict['tel']
KeyError: 'tel'
View Code
>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))
SDIBT
>>> aDict['score'] = aDict.get('score',[])
>>> aDict['score'].append(98)
>>> aDict['score'].append(97)
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
View Code
>>> aDict={'name':'Dong', 'sex':'male', 'age':37}
>>> for item in aDict.items():         #输出字典中所有元素
       print(item)
('age', 37)
('name', 'Dong')
('sex', 'male')

>>> for key in aDict:                       #不加特殊说明,默认输出键
    print(key)
age
name
sex
>>> for key, value in aDict.items():             #序列解包用法
       print(key, value)
age 37
name Dong
sex male

>>> aDict.keys()                                          #返回所有键
dict_keys(['name', 'sex', 'age'])

>>> aDict.values()                                       #返回所有值
dict_values(['Dong', 'male', 37])
View Code

2.3.3 字典元素的添加与修改

>>> aDict['age'] = 38                      #修改元素值
>>> aDict
{'age': 38, 'name': 'Dong', 'sex': 'male'}
>>> aDict['address'] = 'SDIBT'        #增加新元素
>>> aDict
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}
View Code
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.items()
dict_items([('age', 37), ('score', [98, 97]), ('name', 'Dong'), ('sex', 'male')])
>>> aDict.update({'a':'a','b':'b'})
>>> aDict
{'a': 'a', 'score': [98, 97], 'name': 'Dong', 'age': 37, 'b': 'b', 'sex': 'male'}
View Code

2.3.5 有序字典

>>> x = dict()                   #无序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
{'b': 5, 'c': 8, 'a': 3}
>>> import collections
>>> x = collections.OrderedDict() #有序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
OrderedDict([('a', 3), ('b', 5), ('c', 8)])
View Code

2.3.6 字典推导式

>>> s = {x:x.strip() for x in ('  he  ', 'she    ', '    I')}
>>> s
{'  he  ': 'he', '    I': 'I', 'she    ': 'she'}
>>> for k, v in s.items():
           print(k, ':', v)

  he   : he
    I : I
she     : she 

>>> {i:str(i) for i in range(1, 5)}
{1: '1', 2: '2', 3: '3', 4: '4'}
>>> x = ['A', 'B', 'C', 'D']
>>> y = ['a', 'b', 'b', 'd']
>>> {i:j for i,j in zip(x,y)}
{'A': 'a', 'C': 'b', 'B': 'b', 'D': 'd'}
View Code

2.4 集合

2.4.1 集合的创建与删除

>>> a = {3, 5}
>>> a.add(7)                  #向集合中添加元素
>>> a
{3, 5, 7}
View Code
>>> a_set = set(range(8,14))
>>> a_set
{8, 9, 10, 11, 12, 13}
>>> b_set = set([0, 1, 2, 3, 0, 1, 2, 3, 7, 8])     #自动去除重复
>>> b_set
{0, 1, 2, 3, 7, 8}
>>> c_set = set()                                              #空集合
>>> c_set
set()
View Code

2.4.2 集合操作

  Python集合支持交集、并集、差集等运算

>>> a_set = set([8, 9, 10, 11, 12, 13])
>>> b_set = {0, 1, 2, 3, 7, 8}
>>> a_set | b_set                             #并集
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set.union(b_set)                   #并集
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set & b_set                           #交集
{8}
>>> a_set.intersection(b_set)          #交集
{8}
>>> a_set.difference(b_set)             #差集
{9, 10, 11, 12, 13}
>>> a_set - b_set
{9, 10, 11, 12, 13}
View Code
>>> a_set.symmetric_difference(b_set)    #对称差集
{0, 1, 2, 3, 7, 9, 10, 11, 12, 13}
>>> a_set ^ b_set
{0, 1, 2, 3, 7, 9, 10, 11, 12, 13}
>>> x = {1, 2, 3}
>>> y = {1, 2, 5}
>>> z = {1, 2, 3, 4}
>>> x.issubset(y)                                     #测试是否为子集
False
>>> x.issubset(z)
True
>>> {3} & {4}
set()
>>> {3}.isdisjoint({4})                               #如果两个集合的交集为空,返回True
True
View Code
>>> x = {1, 2, 3}
>>> y = {1, 2, 5}
>>> z = {1, 2, 3, 4}
>>> x < y                                        #比较集合大小/包含关系
False
>>> x < z                                         #真子集
True
>>> y < z
False
>>> {1, 2, 3} <= {1, 2, 3}                #子集
True
View Code
>>> import random
>>> listRandom = [random.choice(range(10000)) for i in range(100)]
>>> noRepeat = []
>>> for i in listRandom :
      if i not in noRepeat :
         noRepeat.append(i)
>>> len(listRandom)
>>> len(noRepeat)
>>> newSet = set(listRandom)
View Code

2.5 再谈内置方法sorted()

>>> persons = [{'name':'Dong', 'age':37}, {'name':'Zhang', 'age':40}, {'name':'Li', 'age':50}, {'name':'Dong', 'age':43}]
>>> print(persons)
[{'age': 37, 'name': 'Dong'}, {'age': 40, 'name': 'Zhang'}, {'age': 50, 'name': 'Li'}, {'age': 43, 'name': 'Dong'}]
#使用key来指定排序依据,先按姓名升序排序,姓名相同的按年龄降序排序
>>> print(sorted(persons, key=lambda x:(x['name'], -x['age'])))
[{'age': 43, 'name': 'Dong'}, {'age': 37, 'name': 'Dong'}, {'age': 50, 'name': 'Li'}, {'age': 40, 'name': 'Zhang'}]
>>> phonebook = {'Linda':'7750', 'Bob':'9345', 'Carol':'5834'}
>>> from operator import itemgetter
>>> sorted(phonebook.items(), key=itemgetter(1)) #按字典中元素值进行排序
[('Carol', '5834'), ('Linda', '7750'), ('Bob', '9345')]
>>> sorted(phonebook.items(), key=itemgetter(0)) #按字典中元素的键进行排序
[('Bob', '9345'), ('Carol', '5834'), ('Linda', '7750')]
>>> gameresult = [['Bob', 95.0, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 83.5, 'A'], ['Rob', 89.3, 'E']]
>>> sorted(gameresult, key=itemgetter(0, 1)) #按姓名升序,姓名相同按分数升序排序
[['Alan', 86.0, 'C'], ['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Rob', 89.3, 'E']]
>>> sorted(gameresult, key=itemgetter(1, 0)) #按分数升序,分数相同的按姓名升序排序
[['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E'], ['Bob', 95.0, 'A']]
>>> sorted(gameresult, key=itemgetter(2, 0)) #按等级升序,等级相同的按姓名升序排序
[['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E']]
>>> gameresult = [{'name':'Bob', 'wins':10, 'losses':3, 'rating':75.0},
                              {'name':'David', 'wins':3, 'losses':5, 'rating':57.0},
                              {'name':'Carol', 'wins':4, 'losses':5, 'rating':57.0},
                              {'name':'Patty', 'wins':9, 'losses':3, 'rating':72.8}]
>>> sorted(gameresult, key=itemgetter('wins', 'name')) 
#按'wins'升序,该值相同的按'name'升序排序
[{'wins': 3, 'rating': 57.0, 'name': 'David', 'losses': 5}, {'wins': 4, 'rating': 57.0, 'name': 'Carol', 'losses': 5}, {'wins': 9, 'rating': 72.8, 'name': 'Patty', 'losses': 3}, {'wins': 10, 'rating': 75.0, 'name': 'Bob', 'losses': 3}]
View Code
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']
View Code

2.6 复杂数据结构

2.6.1 堆

>>> import heapq                    #heapq和random是Python标准库
>>> import random
>>> data=range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.choice(data)             #随机选择一个元素
9
>>> random.shuffle(data)            #随机打乱顺序
>>> data
[6, 1, 3, 4, 9, 0, 5, 2, 8, 7]
>>> heap=[]
>>> for n in data:                  #建堆
    heapq.heappush(heap,n)
>>> heap
[0, 2, 1, 4, 7, 3, 5, 6, 8, 9]
>>> heapq.heappush(heap,0.5)        #入堆,自动重建
>>> heap
[0, 0.5, 1, 4, 2, 3, 5, 6, 8, 9, 7]
>>> heapq.heappop(heap)             #出堆,自动重建
0
>>> myheap=[1,2,3,5,7,8,9,4,10,333]
>>> heapq.heapify(myheap)             #建堆
>>> myheap
[1, 2, 3, 4, 7, 8, 9, 5, 10, 333]
>>> heapq.heapreplace(myheap,6)       #弹出最小元素,同时插入新元素
1
>>> myheap
[2, 4, 3, 5, 7, 8, 9, 6, 10, 333]
>>> heapq.nlargest(3, myheap)         #返回前3个最大的元素
[333, 10, 9]
>>> heapq.nsmallest(3, myheap)        #返回前3个最小的元素
[2, 3, 4]
View Code

2.6.2 队列

>>> import queue        #queue是Python标准库
>>> q=queue.Queue()
>>> q.put(0)            #入队
>>> q.put(1)
>>> q.put(2)
>>> q.queue
deque([0, 1, 2])
>>> q.get()             #出队
0
>>> q.queue             #查看队列中的元素
deque([1, 2])
>>> q.get()
1
>>> q.queue
deque([2])
View Code
>>> from queue import Queue    #LILO队列
>>> q = Queue()                #创建队列对象
>>> q.put(0)                   #在队列尾部插入元素
>>> q.put(1)
>>> q.put(2)
>>> print(q.queue)             #查看队列中所有元素
deque([0, 1, 2])
>>> q.get()                    #返回并删除队列头部元素
0
>>> q.get()
1
View Code
>>> from queue import LifoQueue  #LIFO队列
>>> q = LifoQueue()              #创建LIFO队列对象
>>> q.put(1)                     #在队列尾部插入元素
>>> q.put(2)
>>> q.put(3)
>>> q.queue                      #查看队列中所有元素
[1, 2, 3]
>>> q.get()                      #返回并删除队列尾部元素
3
>>> q.get()
2
>>> q.queue
[1]
>>> q.get()                      #对空队列调用get()方法会阻塞当前线程
View Code
>>> from queue import PriorityQueue   #优先级队列
>>> q = PriorityQueue()                         #创建优先级队列对象
>>> q.put(3)                       #插入元素
>>> q.put(8)                       #插入元素
>>> q.put(100)
>>> q.queue                       #查看优先级队列中所有元素
[3, 8, 100]
>>> q.put(1)                       #插入元素,自动调整优先级队列
>>> q.put(2)
>>> q.queue
[1, 2, 100, 8, 3]
>>> q.get()                        #返回并删除优先级最低的元素
1
>>> q.get()                        #请多执行几次该语句并观察返回的数据
2
View Code
>>> from collections import deque
>>> q = deque(maxlen=5)               #创建双端队列
>>> for item in [3, 5, 7, 9, 11]:          #添加元素
    q.append(item)
>>> q.append(13)                             #队列满,自动溢出
>>> q.append(15)
>>> q
deque([7, 9, 11, 13, 15], maxlen=5)
>>> q.appendleft(5)                          #从左侧添加元素,右侧自动溢出
>>> q
deque([5, 7, 9, 11, 13], maxlen=5)
View Code

2.6.3 栈

>>> myStack = []
>>> myStack.append(3)
>>> myStack.append(5)
>>> myStack.append(7)
>>> myStack
[3, 5, 7]
>>> myStack.pop()
7
>>> myStack.pop()
5
>>> myStack.pop()
3
>>> myStack.pop()
出错
View Code
class Stack:
    def __init__(self, size = 10):
        self._content = []                 #使用列表存放栈的元素
        self._size = size                  #初始栈大小
        self._current = 0                  #栈中元素个数初始化为0
        
    def empty(self):
        self._content = []
        self._current = 0
        
    def isEmpty(self):
        if not self._content:
            return True
        else:
            return False
View Code

 

标签:11,Code,Python,元素,aList,列表,序列,View
来源: https://www.cnblogs.com/BlairGrowing/p/15423267.html