序列
# 适用于列表、元组、字符串,以列表为例
# 索引
# 从前向后 0 1 2 ...
# 从后向前 -1 -2 -3 ...
>>>greeting = 'Hello'
>>>greeting[0]
'H'
>>>greeting[-1]
'o'
>>>'Hello'[1]
'e'
>>>fourth = input('Year: ')[3]
Year: 2005
>>>fourth
'5'
# 切片
>>>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>numbers[3:6]
[4, 5, 6]
>>>numbers[0:1]
[1]
>>>numbers[-3:0]
[]
>>>numbers[-3:]
[8, 9, 10]
>>>numbers[:3]
[1, 2, 3]
>>>numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>numbers[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>numbers[0:10:2]
[1, 3, 5, 7, 9]
>>>numbers[3:6:3]
[4]
>>>numbers[::4]
[1, 5, 9]
>>>numbers[8:3:-1]
[9, 8, 7, 6, 5]
>>>numbers[10:0:-2]
[10, 8, 6, 4, 2]
>>>numbers[0:10:-2]
[]
>>>numbers[::-2]
[10, 8, 6, 4, 2]
>>>numbers[5::-2]
[6, 4, 2]
>>>numbers[:5:-2]
[10, 8]
# 序列加法
>>>a = [1, 2, 3]
>>>b = [4, 5, 6]
>>>a + b
[1, 2, 3, 4, 5, 6]
>>>a.extend(b)
>>>a
[1, 2, 3, 4, 5, 6]
# 序列乘法
>>>[42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
# 成员运算符in
>>>1 in [1, 2, 3]
True
>>>4 in [1, 2, 3]
False
# 统计函数
>>>numbers = [100, 34, 678]
>>>len(numbers)
3
>>>max(numbers)
678
>>>min(numbers)
34
>>>max(2, 3)
3
>>>min(9, 3, 2, 5)
2
列表
# 定义
>>>names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
# 增
>>>names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>>names.append('tmp1')
>>>print(names)
['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl', 'tmp1']
# extend效率高于a = a + b,等效于a[len(a):] = b(可读性低)
>>>names.extend(['tmp2', 'tmp3'])
>>>print(names)
['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl', 'tmp1', 'tmp2', 'tmp3']
# 等效于names[0:0] = ['tmp4'](可读性低)
>>>names.insert(0, 'tmp4')
>>>print(names)
['tmp4', 'Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl', 'tmp1', 'tmp2', 'tmp3']
# 删
# 等效于names[0:1] = []
>>>del names[0]
>>>print(names)
['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl', 'tmp1', 'tmp2', 'tmp3']
# 等效于names[0:2] = []
>>>del names[0:2]
>>>print(names)
['Cecil', 'Dee-Dee', 'Earl', 'tmp1', 'tmp2', 'tmp3']
# 若不存在Earl将报错
>>>names.remove('Earl')
>>>print(names)
['Cecil', 'Dee-Dee', 'tmp1', 'tmp2', 'tmp3']
>>>names.pop()
'tmp3'
>>>print(names)
['Cecil', 'Dee-Dee', 'tmp1', 'tmp2']
>>>names.pop(0)
'Cecil'
>>>print(names)
['Dee-Dee', 'tmp1', 'tmp2']
>>>names.clear()
>>>print(names)
[]
# 改
>>>x = [1, 1, 1]
>>>x[1] = 2
>>>x
[1, 2, 1]
# 给切片赋值
>>>name = list('Perl')
>>>name
['P', 'e', 'r', 'l']
#'ar'长度<=names[2:]的长度,name的长度不变
>>>name[2:] = list('ar')
>>>name
['P', 'e', 'a', 'r']
>>>name = list('Perl')
#'ython'长度>names[1:]的长度,name的长度变大
>>>name[1:] = list('ython')
>>>name
['P', 'y', 't', 'h', 'o', 'n']
# 查
# index 不存在将报错
>>>knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>>knights.index('who')
4
# count
>>>['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>>x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>>x.count(1)
2
>>>x.count([1, 2])
1
# 转换
>>>t = ['1', '2', '3']
>>>tuple(t)
('1', '2', '3')
>>>''.join(t)
'123'
>>>set(t)
{'3', '2', '1'}
# 数据shape为任意行2列,内外层可以为[] () '' {} 即列表 元组 字符串 集合
>>>dict(zip(['1', '2', '3'], ['4', '5', '6']))
{'1': '4', '2': '5', '3': '6'}
>>>dict([['1', '4'], ['2', '5'], ['3', '6']])
{'1': '4', '2': '5', '3': '6'}
>>>dict([('1', '4'), ('2', '5'), ('3', '6')])
{'1': '4', '2': '5', '3': '6'}
>>>dict(['14', '25', '36'])
{'1': '4', '2': '5', '3': '6'}
# {}集合顺序不定造成转换成的字典 键-值 不定
>>>dict([{'1', '4'}, {'2', '5'}, {'3', '6'}])
{'1': '4', '5': '2', '6': '3'}
# 其他
# copy
>>>a = [1, 2, 3]
>>>b = a
>>>b[1] = 4
>>>a
[1, 4, 3]
>>>a = [1, 2, 3]
>>>b = a.copy()
>>>b[1] = 4
>>>a
[1, 2, 3]
# reverse
>>>x = [1, 2, 3]
>>>x.reverse()
>>>x
[3, 2, 1]
#reversed函数返回一个迭代器,按相反的顺序迭代序列;list将返回的对象转换为列表;
>>>x = [1, 2, 3]
>>>list(reversed(x))
[3, 2, 1]
# sort & sorted
>>>x = [4, 6, 2, 1, 7, 9]
>>>x.sort()
>>>x
[1, 2, 4, 6, 7, 9]
>>>x = [4, 6, 2, 1, 7, 9]
>>>y = sorted(x)
>>>x
[4, 6, 2, 1, 7, 9]
>>>y
[1, 2, 4, 6, 7, 9]
>>>sorted('Python')
['P', 'h', 'n', 'o', 't', 'y']
>>>x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
>>>x.sort(key=len)
>>>x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>>x = [4, 6, 2, 1, 7, 9]
>>>x.sort(reverse=True)
>>>x
[9, 7, 6, 4, 2, 1]
# 栈
1)出栈pop(),入栈append(),即列表尾为栈顶
2)出栈pop(0),入栈insert(0, key),即列表首为栈顶
# 队列
1)出队pop(0),入队append(),即列表头为队头,列表尾为队尾
2)出队pop(),入队insert(0, key),即列表头为队尾,列表尾为队头
3)使用模块collections中的deque,在后续学习中详细说明
元组
# 定义
>>>1, 2, 3
(1, 2, 3)
>>>(1, 2, 3)
(1, 2, 3)
>>>()
()
>>>42,
(42,)
>>>(42,)
(42,)
# 不允许 增 删 改
# 查
>>>(1, 2, 3).index(2)
1
>>>(1, 2, 3).count(2)
1
# 转换
>>>t = ('1', '2', '3')
>>>list(t)
['1', '2', '3']
>>>''.join(t)
'123'
>>>set(t)
{'3', '2', '1'}
# 数据shape为任意行2列,内外层可以为[] () '' {} 即列表 元组 字符串 集合
>>>dict(zip(('1', '2', '3'), ('4', '5', '6')))
{'1': '4', '2': '5', '3': '6'}
>>>dict((['1', '4'], ['2', '5'], ['3', '6']))
{'1': '4', '2': '5', '3': '6'}
>>>dict((('1', '4'), ('2', '5'), ('3', '6')))
{'1': '4', '2': '5', '3': '6'}
>>>dict(('14', '25', '36'))
{'1': '4', '2': '5', '3': '6'}
# {}集合顺序不定造成转换成的字典 键-值 不定
>>>dict(({'1', '4'}, {'2', '5'}, {'3', '6'}))
{'1': '4', '5': '2', '6': '3'}
# 其他
字符串
# 定义
#单/双引号都表示字符串,正确的输入示例
>>>"Hello, World!"
'Hello, World!'
>>>'Hello, World!'
'Hello, World!'
#单双引号都有效是为了能在不使用引号转义的情况下,在字符串中使用单双引号,例如:
>>>"Let's go!"
"Let's go!"
#如果仅使用单引号,即>>>'Let's go!',解释器将认为Let为字符串,从s开始即报错,输出
#SyntaxError: invalid syntax,或者使用引号转义
>>>'Let\'s go!'
"Let's go!"
#再例如
>>>'"Hello, world!" she said'
'"Hello, world!" she said'
#可以写作
>>>"\"Hello, world!\" she said"
'"Hello, world!" she said'
# 字符串拼接
>>>"Let's say " '"Hello, world!"'
'Let\'s say "Hello, world!"'
>>>"Hello, "+"world!"
'Hello, world!'
>>>x = "Hello, "
>>>y = "world!"
>>>x + y
'Hello, world!'
# 长字符串(可以跨行,用'''''')
>>>print('''This is a very long string. It continues here.
And it's not over yet. "Hello, world"
Still here.''')
# 原始字符串(用r)
>>>print('C:\nowhere')
C:
owhere
>>>print(r'C:\nowhere')
C:\nowhere
>>>print(r'This is illegal\')
SyntaxError: EOL while scanning string literal
# 不允许 增 删 改
# 查
>>>t = "Hello, World!"
>>>t.index('o')
4
>>>t.rindex('o')
8
>>>t = "Hello, World!"
>>>t.index('e')
1
>>>t.rindex('e')
1
>>>t.count('o')
2
>>>t.count('e')
1
# 转换
t = "Hello, World!"
list(t)
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
tuple(t)
('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
set(t)
{',', ' ', '!', 'd', 'r', 'W', 'e', 'l', 'o', 'H'}
dict(zip('123', '456'))
{'1': '4', '2': '5', '3': '6'}
# 其他
# 格式化字符串
1) format % values
2) Template
3) "".format()
>>>format = "Hello, %s. %s enough for ya?"
>>>values = ('world', 'Hot')
>>>format % values
'Hello, world. Hot enough for ya?'
>>>from string import Template
>>>tmp1 = Template("Hello, $who! $what enough for ya?")
>>>tmp1.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'
>>>"{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>>"{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
>>>"{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'
>>>from math import pi
>>>"{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'
>>>"{name} is approximately {value}.".format(value=pi, name="π")
'π is approximately 3.141592653589793.'
>>>from math import e
>>>f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
# 等价于:
>>>"Euler's constant is roughly {e}.".format(e=e)
"Euler's constant is roughly 2.718281828459045."
映射
# 定义
>>>dict(name='Gumby', age = 42)
{'name': 'Gumby', 'age': 42}
>>>{'name': 'Gumby', 'age': 42}
{'name': 'Gumby', 'age': 42}
# fromkeys
>>>{}.fromkeys(['name', 'age'])
{'name': None, 'age': None}
>>>dict.fromkeys(['name', 'age'])
{'name': None, 'age': None}
# 指定默认值
>>>dict.fromkeys(['name', 'age'], 'unknown')
{'name': 'unknown', 'age': 'unknown'}
# 增
>>>d = {1: 2, 3: 4, 5: 6}
# 不存在键,插入键值对
>>>d.update({8: 7})
>>>d
{1: 2, 3: 4, 5: 6, 8: 7}
>>>d[9] = 10
>>>d
{1: 2, 3: 4, 5: 6, 8: 7, 9: 10}
# 删
>>>d = {1: 2, 3: 4, 5: 6}
# 弹出指定键的值
>>>d.pop(3)
4
>>>d
{1: 2, 5: 6}
# 随机弹出项
>>>d.popitem()
(5, 6)
>>>d
{1: 2}
>>>d.clear()
>>>d
{}
# 改
>>>d = {1: 2, 3: 4, 5: 6}
# 存在键,更新值
>>>d.update({5: 7})
>>>d
{1: 2, 3: 4, 5: 7}
>>>d[5] = 8
>>>d
{1: 2, 3: 4, 5: 8}
# 查
# 转换(仅针对键)
>>>d = {'1': '2', '3': '4', '5': '6'}
>>>d
{'1': '2', '3': '4', '5': '6'}
>>>list(d)
['1', '3', '5']
>>>tuple(d)
('1', '3', '5')
>>>''.join(d)
'135'
>>>set(d)
{'5', '1', '3'}
# 显式针对值
>>>list(d.values())
['2', '4', '6']
>>>tuple(d.values())
('2', '4', '6')
>>>''.join(d.values())
'246'
>>>set(d.values())
{'6', '2', '4'}
>>>d = {'1': '2', '3': '4', '5': '6'}
>>>del d['5']
>>>d
{'1': '2', '3': '4'}
# 其他
>>>d = {1: 2, 3: 4, 5: 6}
>>>d.items()
dict_items([(1, 2), (3, 4), (5, 6)])
>>>d.keys()
dict_keys([1, 3, 5])
>>>d.values()
dict_values([2, 4, 6])
>>>d.get(1)
2
# 不存在7,返回None
>>>d.get(7)
# 不存在7,返回值'aaa'
>>>d.get(7, 'aaa')
'aaa'
# setdefault
>>>d = {1: 2, 3: 4, 5: 6}
# 存在键5,返回对应的值6
>>>d.setdefault(5, 'aaa')
6
>>>d
{1: 2, 3: 4, 5: 6}
# 不存在键7,插入键值对 7:'bbb',返回新值'bbb'
>>>d.setdefault(7, 'bbb')
'bbb'
>>>d
{1: 2, 3: 4, 5: 6, 7: 'bbb'}
>>>phonebook = {'Beth':'9102', 'Alice':'2341', 'Cecil':'3258'}
>>>phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
"Cecil's phone number is {Cecil}.".format_map(phonebook)
"Cecil's phone number is 3258."
集合
# 定义
s = {1, 2, 3, 4}
# 增
>>>s = {1, 2, 3, 4}
>>>s.add(4)
>>>s
{1, 2, 3, 4}
>>>s.add(5)
>>>s
{1, 2, 3, 4, 5}
>>>s.update({4, 5})
>>>s
{1, 2, 3, 4, 5}
>>>s.update({6, 7})
>>>s
{1, 2, 3, 4, 5, 6, 7}
# 删
>>>s.remove(7)
>>>s
{1, 2, 3, 4, 5, 6}
# 删除失败报错
>>>s.remove(7)
Traceback (most recent call last):
File "E:\anaconda\envs\py37tfcpu\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
KeyError: 7
>>>s.discard(6)
>>>s
{1, 2, 3, 4, 5}
# 删除失败不报错
>>>s.discard(6)
>>>s
{1, 2, 3, 4, 5}
>>>s.pop()
1
>>>s
{2, 3, 4, 5}
>>>s.clear()
>>>s
set()
# 不允许 改
# 查
>>>1 in {1, 2, 3, 4}
True
# 转换
>>>t = {'1', '2', '3', '4'}
>>>list(t)
['1', '2', '4', '3']
>>>tuple(t)
('1', '2', '4', '3')
>>>''.join(t)
'1243'
# 集合顺序不定,造成生成的字典 键-值 不定
>>>dict(zip({'1', '2', '3'}, {'4', '5', '6'}))
{'1': '5', '2': '6', '3': '4'}
>>>dict({['1', '4'], ['2', '5'], ['3', '6']})
TypeError: unhashable type: 'list'
>>>dict({('1', '4'), ('2', '5'), ('3', '6')})
{'1': '4', '3': '6', '2': '5'}
>>>dict({'14', '25', '36'})
{'3': '6', '1': '4', '2': '5'}
>>>dict({{'1', '4'}, {'2', '5'}, {'3', '6'}})
TypeError: unhashable type: 'set'
# 其他
# 并集
s1 = {1, 2, 3, 4}
s2 = {5, 2, 3, 7}
# {1, 2, 3, 4, 5, 7}
# {1, 2, 3, 4, 5, 7}
# {1, 2, 3, 4}
print(s1 | s2)
print(s1.union(s2))
print(s1)
# 交集
s1 = {1, 2, 3, 4}
s2 = {5, 2, 3, 7}
# {2, 3}
# {2, 3}
# {1, 2, 3, 4}
# None
# {2, 3}
print(s1 & s2)
print(s1.intersection(s2))
print(s1)
print(s1.intersection_update(s2))
print(s1)
# 查集
s1 = {1, 2, 3, 4}
s2 = {5, 2, 3, 7}
# {1, 4}
# {1, 4}
# {1, 2, 3, 4}
# None
# {1, 4}
print(s1 - s2)
print(s1.difference(s2))
print(s1)
print(s1.difference_update(s2))
print(s1)
# 对称差集
s1 = {1, 2, 3, 4}
s2 = {5, 2, 3, 7}
# {1, 4, 5, 7}
# {1, 4, 5, 7}
# {1, 2, 3, 4}
# None
# {1, 4, 5, 7}
print(s1 ^ s2)
print(s1.symmetric_difference(s2))
print(s1)
print(s1.symmetric_difference_update(s2))
print(s1)
# 交集是空集
>>>{1, 2}.isdisjoint({2, 3})
False
>>>{1, 2}.isdisjoint({3, 4})
True
# 前包含于后
>>>{1, 2}.issubset({1, 2, 3, 4})
True
# 前包含后
>>>{1, 2, 3, 4}.issuperset({1, 2})
True
堆(小顶堆)
不属于Python内置的容器,需要通过heapq模块实现
堆是一种优先队列,能够以任意顺序添加对象并随时(可能是在两次添加对象之间)找出(并删除)最小的元素(小顶堆)。相比于列表方法min,这样做的效率要高很多。
函数 | 描述 |
---|---|
heappush(heap, x) | 将x压入堆中(不要应用于普通列表,只能应用于具备堆特征的列表) |
heappop(heap) | 从堆中弹出最小的元素并返回 |
heapify(heap) | 让普通列表具备堆特征 |
heapreplace(heap, x) | 弹出最小的元素,并将x压入堆中;相当于先heappop(heap)再heappush(heap, x),但效率比前面更高 |
nlargest(n, iter) | 返回可迭代对象iter中n个最大的元素(不弹出)(可通过先排序再切片来完成,但堆算法速度更快使用内存更少) |
nsmallest(n, iter) | 返回可迭代对象iter中n个最小的元素(不弹出)(可通过先排序再切片来完成,但堆算法速度更快使用内存更少) |
基本数据类型
from heapq import *
from random import shuffle
data = list(range(10))
shuffle(data)
heap = []
# 开始heap为空(具备堆特征),不断向其中添加元素(每添加一个元素heappush函数会使添加后的列表重新具备堆特征)
for n in data:
heappush(heap, n)
print(heap)
# [0, 2, 1, 4, 3, 8, 7, 9, 5, 6]
heappush(heap, 0.5)
print(heap)
# [0, 0.5, 1, 4, 2, 8, 7, 9, 5, 6, 3]
print(heappop(heap))
print(heap)
# 0
# [0.5, 2, 1, 4, 3, 8, 7, 9, 5, 6]
print(heapreplace(heap, 0.6))
print(heap)
# 0.5
# [0.6, 2, 1, 4, 3, 8, 7, 9, 5, 6]
print(nlargest(3, heap))
print(heap)
# [9, 8, 7]
# [0.6, 2, 1, 4, 3, 8, 7, 9, 5, 6]
print(nsmallest(3, heap))
print(heap)
# [0.6, 1, 2]
# [0.6, 2, 1, 4, 3, 8, 7, 9, 5, 6]
print(data)
# [4, 5, 7, 0, 6, 8, 1, 9, 3, 2]
heapify(data)
print(data)
# [0, 2, 1, 3, 4, 8, 7, 9, 5, 6]
自定义数据类型
from heapq import *
from random import shuffle
class Test:
def __init__(self, num):
self.num = num
def __str__(self):
return f"值为{self.num}"
def __lt__(self, other):
"""
重载 <
若 self.num < other.num,则self < other
:param other:
:return:
"""
return self.num < other.num
data = list(range(10))
shuffle(data)
objects = [Test(i) for i in data]
for item in objects:
print(item)
print('----------------------------')
heapify(objects)
while len(objects) > 0:
print(heappop(objects))
# 值为4
# 值为6
# 值为5
# 值为8
# 值为3
# 值为0
# 值为7
# 值为9
# 值为1
# 值为2
# ----------------------------
# 值为0
# 值为1
# 值为2
# 值为3
# 值为4
# 值为5
# 值为6
# 值为7
# 值为8
# 值为9