字典
其实就是C++里面的map。key 和 value的映射
1 2 3
| dict1 = {"李宁":"一切皆有可能" , "耐克":"Just do it"} for x in dict1 : print("%s -> %s" % (x , dict[x]))
|
空字典直接用大括号即可
1 2
| empty = {} dict1 = {x=1,y=2,z=3}
|
内置方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| dict1 = {} dict1.fromkeys((1,2,3) , "Number") {1:'Number', 2:'Number', 3:'Number'}
dict2 = {} dict2.fromkeys((1,2,3) , ("a","b","c")) {1:'a', 2:'b', 3:'c'}
dict1.keys() dict1.values() dict1.items()
dict1.get(x) dict1.get(x,"没有")
31 in dict1 32 in dict2
dict1.clear()
a = {x=1,y=2,z=3} b.copy(a)
a.setdefault(3)
a.updata(x = 2)
|
打包
1 2 3
| def test(**params) : print("有 %d 个参数" % len(params)) print("他们分别是:" , params)
|
集合
其实就是C++中的set,也用大括号但是没有映射关系
会自动去重、从小到大排序
1 2 3
| list1 = [1, 3, 3, 2] list1 = list(set(list1)) -> list1 = [1, 2, 3]
|
添加删除
1 2
| set1.add(1) set1.remove(1)
|
冻结集合
1
| set1 = frozenset({1,2,3})
|