python学习笔记(基础篇03)
小扩展
可变与不可变数据类型
a = 10
b = a
b = 15
注:a =10 在内存中开辟一个存放整形对象10的空间,并将a指向该内存空间
b = a 将b指向与a 相同的内存空间
b = 15 将b指向整型对象15的空间
这里并不是改变了10这个对象,而是将b指向了另一整型对象,所以说整型是不可变数据类型
不可变:整形,字符串,元组
可变:列表,字典
这里顺便提一下可哈希与不可哈希
可哈希与不可哈希
如果一个对象在自己的生命周期中有一哈希值(hash value)是不可改变的,那么它就是可哈希的(hashable)的,因为这些数据结构内置了哈希值,每个可哈希的对象都内置了__hash__方法,所以可哈希的对象可以通过哈希值进行对比,也可以作为字典的键值和作为set函数的参数。所有python中所有不可改变的的对象(imutable objects)都是可哈希的,比如字符串,元组,也就是说可改变的容器如字典,列表不可哈希(unhashable)。我们用户所定义的类的实例对象默认是可哈希的(hashable),它们都是唯一的,而hash值也就是它们的id()。
即: 可哈希 —> 不可修改
不可哈希 —> 可修改
========================================
1.元组(不可修改有序)
元组又称只读列表,元素值可以被查询,不能被修改
定义: a = () #空元组
a = (1,) #单一元素尽量在后面加一逗号
元组用‘,’(即逗号 ) 来代表
2.字典(可修改无序)
由一对对键值组成,键值中间用‘:’ 连接,用{}表示
键: 要求是不可变类型,唯一
值:任意类型
初始化
(1):dict1 = {‘name’:’hack‘,}用‘ {} ’来初始化
(2):dict()方法
官方:
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
方法
(1)setdefault()
"""
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
"""
即:
dic2 = {'name':'hack', 'age':20}
b = dic2.setdefault('age','19') #返回20
# b = dic2.setdefault('hobby','19') #返回19
print(b)
(2)查 操作
dic = {'name': 'hack', 'age': 20, 'hobby': 'girl'}
print(dic.keys())
print(dic.values())
print(dic.items()) # dict_items([('name', 'hack'), ('age', 20), ('hobby', 'girl')])
keys()方法返回所有键, 类型为’dict_keys’
values()方法返回所有值
items()方法返回个列表,每个键值存放在一个元组中
(3)改 操作
dic2 = {'name': 'Aaron', 'age': 20, 'hobby': 'girl'}
dic2['age'] = 19 #通过字典的键来更改对应值
dic3 ={'name':'Aaron', 'height':180}
dic2.update(dic3) #类似于列表的extend()方法,将其他字典插入
print(dic2)
(4)删 操作
del #del dic[‘name’] 删除一个键值对
clear() #清空列表
pop() 和 popitem():
都具有返回值,pop()删除指定键值,popitem()删除随机键值
dic4 = {'name': 'Aaron', 'age': 20, 'hobby': 'girl'}
# ret = dic4.pop('age')
# print(dic4) # {'name': 'Aaron', 'hobby': 'girl'}
# print(ret) # 20
ret = dic4.popitem()
print(dic4)
print(ret) # ('hobby', 'girl')
(5)字典的遍历
for i in dic4:
print(i) # 默认遍历键
print(i, dic4[i])
3.字符串(不可修改)
(1).‘ * ’重复打印
print('Hello,world '*20)
即重复打印20次hello,world
(2).切片 同列表
print('Hello,world '[2:])
输出结果:llo,world
(3). ‘ in ’判断内容是否在容器里面,返回True 或者 False
(4). 格式化字符串
print('%s is a good student'% 'hack')
结果:hack is a good student
(5). 字符串拼接 join()方法 (将列表转换为字符串)
'''
'.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
'''
a = '123'
b = 'abc'
c = ''.join([a, b])
print(c) # 123abc
用 ‘’ 里的字符串将列表各元素拼接起来,并返回拼接后的字符串
(6)capitalize() 给字符串首字母大写
(7)startswith()
st = 'Hello,world'
print(st.startswith('He')) # True
判断字符串是否以某个内容开头,是返回True, 否返回False
(8) find() 查找某元素在字符串中的位置,并返回索引值
st = 'Hello,world'
print(st.find('l')) # 2
**(9) format() 用定义的值来替换{}里的变量 **
"""
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
print('Hello, {name} is {age} years old.'.format(name='hack', age=18))
# Hello, hack is 18 years old.
(10) isdigit() 判断是否为整型,是返回True , 否返回False
(11) lower() 大写变小写
upper() 小写变大写
(12)strip() 去掉换行符和空格
print('ac\n'.strip()) # ac
(13) split() 按 ‘ ’ 里去分割字符串 返回一个列表
print('my first prize'.split(' ')) #['my', 'first', 'prize']
(14) center()
print('End'.center(5, '='))
结果: =End=
5代表一共输出5位,不够位用 ‘ ’ 里字符补齐,并将字符串居中输出
==============================================
分割线:上次写的时候忘记写集合,重新编辑后已经加上喽
4.集合(无序不可重复)
特性:互异性:即不存在相同元素
确定性:集合中的元素不可修改(可哈希)
无序性:元素无先后之分
作用:(1)去重(2)做关系测试(并,交,叉)
(1)创建集合(只有这一种方式)
set() -> new empty set object
set(iterable) -> new set object
a = [18, 'hack', 18]
b = set(a)
print(b) #{18, 'hack'}
set()创建可变集合,frozenset()创建不可变集合
注:set()创建的集合是不可哈希的,即是可变集合,可做修改
(2)修改
add() , update() , remove()
b.add(2) #添加一个元素
print(b) #{18, 2, 'hack'}
#用一个可迭代序列更新集合
b.update('abc')
print(b) #{'hack', 'b', 18, 'c', 'a'}
#remove为移除集合中某个元素
(3)集合类型操作符
1.in , not in
2.’ == ‘ 两集合是否等价
‘ != ’ 两集合不等价
‘ < ’ 前者是否为后者子集
‘ > ’ 前者是否为后者父级
3.联合union(): 取并集, ‘ | ’
交叉intersection():取交集 ‘ &’
difference():取差集 ‘ - ’
b1 = set('hack')
b2 = set('hack1')
print(b1.union(b2)) #{'h', 'c', 'k', 'a', '1'}
print(b1.intersection(b2)) #{'h', 'c', 'k', 'a'}
print(b1.difference(b2)) #set()
print(b2.difference(b1)) #{'1'}