一、元组
tuple:tu = (111, 22, 33, 44)
元组里1级元素不可被修改,不能被增加或者删除,可以用索引和切片取值,可以迭代,是有序的
tu = (111, "asd", (11, 22), [(33, 22)], Ture, 33, 44,) #一般写元组时,推荐在最后加入,
1、字符串、列表、元组互换
s = "asdwdasdsad"
li = ["asda", "asdasdaf"]
tu = ("asdas", "asd")
v = tuple(s) #字符串转化元组
v1 = list(tu) #元组转化列表
#不能含有数字
2、count();index()
tu = (12, 54, 88, 45)
tu.count(12) # 指定元素在元组中出现次数
tu.index(54) # 指定元素的索引
二、字典 (dict)
info = {
"k1" : "v1" # 键值对
"k2" : "v2"
}
# 字典的value可以是任何值
info = {
"k1" : 18,
"k2" : True,
"k3" : {
11,
[],
(),
22,
33,
{
"kk1" : "vv1",
"kk2" : "vv2",
"kk3" : (11, 22),
}
},
"k4" : (11, 22, 33, 44)
}
v = info["k3"][5]["kk3"][0] # 索引查找
# 不能切片查找
print(v)
不能做key值的:列表,字典 # bool值可以作为key,True=1,False=0
字典是无序的
1、删除del
info = {
"k1" : 18,
"k2" : True,
"k3" : {
11,
[],
(),
22,
33,
{
"kk1" : "vv1",
"kk2" : "vv2",
"kk3" : (11, 22),
}
},
"k4" : (11, 22, 33, 44)
}
del info["k3"]
print(info)
2、for循环
for item in info: # 默认循环key
print(item)
for item in info.keys(): # 循环key
print(item)
for item in info.values(): # 循环values
print(item)
for key, value in info.items(): #取键值对
print(key, value)
三、字典的方法(keys() values()item())
1、.fromkeys():根据序列,船舰字典,并指定统一的值
v = dict.fromkeys(["k1", 123, "999"], 123)
print(v)
2、get():根据Key获取值,如果值不存在,可指定默认返回值
v = dic.get('k1111', 1111)
print(v)
3、pop():指定删除,并获取值;popitem():随机删除,并获取值
dic = {
"k1": 'v1',
"k2": 'v2'
}
v = dic.pop('k1', 90)
k, v1 = dic.popitem()
print(dic, k, v1, v)
4、setdefault():已存在,不设置,获取当前key对应的值;不存在,设置,获取当前对应的值
dic = {
"k1": 'v1',
"k2": 'v2'
}
v = dic.setdefault('k1111', '123')
print(dic, v)
5、update():更新
dic = {
"k1": 'v1',
"k2": 'v2'
}
dic.update({'k1': '1111', 'k3': 123})
dic.update(k1 = 123, k3 = 345, k5 = "asda")
print(dic)
6、很多可以传字典只是前面加**{}