数据结构(类型)
# 数据结构
# 基本类型
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
# 列表(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/12, 00:46:36