数据结构(类型)
Python 在声明变量时,无需显式声明类型,因此类型无外乎:字符串、整数、浮点数
print(type(1)) # <class 'int'>
print(type(1.1)) # <class 'float'>
print(type("True")) # <class 'str'>
print(type(True)) # <class 'bool'> python的布尔值首字母为大写:True、False
# 字符串
# 字面值 (f)
在字符串前添加 f
或 F
,可在 {
和 }
字符之间输入引用的变量:
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
还可以是使用 Python 表达式:
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.') # 将 pi 舍入到小数点后三位
The value of pi is approximately 3.142.
# 在 ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
还有一些修饰符可以在格式化前转换值。
'!a'
应用ascii()
(opens new window)'!s'
应用str()
(opens new window)'!r'
应用repr()
(opens new window):
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
=
说明符可被用于将一个表达式扩展为 表达式文本=表达式值
的形式。
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
# str.format()
>>> yes_votes = 42_572_654
>>> total_votes = 85_705_149
>>> percentage = yes_votes / total_votes
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
# 基本用法
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
# 定义索引
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
# 关键字参数
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
# 混合写法
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
... other='Georg'))
The story of Bill, Manfred, and Georg.
最佳实践
# 用方括号 '[]' 访问键来完成
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
... 'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 采用 ** 标记的关键字参数传入
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 列表(List)
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.count('apple') # 返回出现次数
fruits.count('tangerine')
fruits.index('banana') # 返回第一个索引,找不到抛异常
fruits.index('banana', 4) # 从 4 号位开始查找下一个 banana
fruits.reverse() # 翻转
fruits
fruits.append('grape') # 追加
fruits
fruits.sort() # 排序
fruits
fruits.pop() # 移除最后一个元素
# del 语句
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
a
del a[2:4]
a
del a[:]
a
del a # 整个变量删除,再引用 a 就会报错
# 元组(不可变列表)
# 定义元组
元组由多个用逗号隔开的值组成,例如:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # 元组可以嵌套:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # 元组是不可变对象:
>>> t[0] = 88888 #报错
>>> # 但它们可以包含可变对象:
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
虽然,元组与列表很像,但使用场景不同,用途也不同。元组是不可变的,列表是可变的。
>>> empty = () # 定义空元组
>>> singleton = 'hello', # 定义1个元素的元组,注意末尾的逗号,没有就是字符串了
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
# 序列解包
# 元组打包
t = 12345, 54321, 'hello!'
# 序列解包
x, y, z = t
# 集合(Set)
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # 显示重复项已被移除
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # 快速成员检测
True
>>> 'crabgrass' in basket
False
>>> # 演示针对两个单词中独有的字母进行集合运算
>>>
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # a 中独有的字母
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # 存在于 a 中但不存在于 b 中的字母
{'r', 'd', 'b'}
>>> a | b # 并集:存在于 a 或 b 中或两者中皆有的字母
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # 交集:同时存在于 a 和 b 中的字母
{'a', 'c'}
>>> a ^ b # 存在于 a 或 b 中但非两者中皆有的字母
{'r', 'd', 'b', 'm', 'z', 'l'}
# 字典(Dict、Map)
# 定义
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
# 其他定义方式:构造函数
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
# 其他定义方式:关键字参数
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
# 遍历(集合)
字典
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
序列
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
集合
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)): # sorted返回一个新的有序列表
... print(f)
...
apple
banana
orange
pear
上次更新: 2024/10/27, 11:59:49