Python-学习之路-06 内置数据结构 list set d

2019-01-28  本文已影响0人  末世狂人

元组

函数

# max min
l = (1,1,3,3,2,5,6,7,7,7)
print(max(l))
print(min(l))
7
1

变量交换法

# 变量交换
a = 1
b = 2

a,b = b,a
print(a)
print(b)
2
1

集合 set

# 集合的定义
s = set()
#或者
# 如果使用{}来定义set,那么大括号中必须要有值,否则定义出来的是dict
s = {1,23,4,5,6,7}
print(type(s))
<class 'set'>
# 集合的遍历操作
s = {"i","love","litinghui",4,5,6}
for i in s:
    print(i,end="  ")
print("")
# 带有元组的集合遍历
s = {(1,2,3),("i","love","litinghui"),(9024,456,"2345")}
for k,m,n in s:
    print(k,"----",m,"-----",n,"----")
    
print("")
for k in s:
    print(k)
4  5  6  i  litinghui  love  
i ---- love ----- litinghui ----
9024 ---- 456 ----- 2345 ----
1 ---- 2 ----- 3 ----

('i', 'love', 'litinghui')
(9024, 456, '2345')
(1, 2, 3)

集合函数或关于集合的函数

# pop
s = {11,21,3,4,5,6,7,8,98}
d = s.pop()
print(d)
print(s)
98
{3, 4, 5, 6, 7, 8, 11, 21}

集合的数学操作

s1 = {1,2,3,4,5,6}
s2 = {4,5,6,7,8}
s = s1-s2
print(s)
{1, 2, 3}

frozenset:冰冻集合

dict 字典

# 字典的常见操作
d = {"one":1,"tow":2,"three":3}
#访问
print(d["one"])
#修改
d["one"] = "eins"
print(d["one"])
#删除
del d["one"]
print(d)
1
eins
{'tow': 2, 'three': 3}
# 成员检测 in\not in
# 成员检测是key的内容
# 遍历
d = {"one":1,"tow":2,"three":3}
for k in d:
    print(d[k]) 
    
for k in d.keys():
    print(d[k])
    
#直接访问值
for v in d.values():
    print(v)
    
# 获取每一个键值对
for k,v in d.items():
    print(k,"--->",v)
1
2
3
1
2
3
1
2
3
one ---> 1
tow ---> 2
three ---> 3
# 字典生成式
d = {"one":1,"tow":2,"three":3}
## 常规的生成式
dd = {k:v for k,v in d.items()}
print(dd)

## 限制条件的生成式
ddd = {k:v for k,v in d.items() if v%2==0}
print(ddd)
{'one': 1, 'tow': 2, 'three': 3}
{'tow': 2}

字典的相关函数

# fromkeys
l = ["one","tow","three"]
d = dict.fromkeys(l,666)
print(d)
{'one': 666, 'tow': 666, 'three': 666}
上一篇下一篇

猜你喜欢

热点阅读