字典的内置函数
1.sorted 排序,让字典的数据按照顺序输出
found = {'a':0,'u':2,'i':0} for keys in found: print(keys) #a u i for keys in sorted(found): print(keys) # a i u
2.items,返回一个键值对列表
found = {'a':0,'u':2,'i':0} for keys in found: print(keys) #a u i for keys,values in found.items(): print("keys = {} and values ={}".format(keys,values)) # keys = a and values =0 # keys = u and values =2 # keys = i and values =0 for keys,values in sorted(found.items()): print("keys = {} and values ={}".format(keys,values)) # keys = a and values =0 # keys = i and values =0 # keys = u and values =2
3.字典初始化函数 setdefault
fruits = ['apples','bananas','pears'] found = {'apples':2,'pears':3} for fruit in fruits: if fruit in found: found[fruit] += 1 else: found[fruit] = 1 print('{}个数为{}'.format(fruit,found[fruit])) # 等价于: for fruit in fruits: found.setdefault(fruit,0) found[fruit] += 1 print('{}个数为{}'.format(fruit,found[fruit]))
集合
特性:不重复,无序
1.union合并集合,将集合A和B合并,去重后创建一个新集合
vowels = set('aeiou') print(vowels) #{'i', 'a', 'u', 'o', 'e'} word = 'hello' u = vowels.union(set(word)) #{'o', 'i', 'u', 'e', 'h', 'a', 'l'}
2.difference,给定两个集合,告诉你哪些元素只在集合A中存在而不在集合B中存在
vowels = set('aeiou') print(vowels) #{'i', 'a', 'u', 'o', 'e'} word = 'hello' l = vowels.difference(set(word)) #{'u', 'a', 'i'}
3.intersection报告共同元素,即集合A和集合B的共同元素
vowels = set('aeiou') print(vowels) #{'i', 'a', 'u', 'o', 'e'} word = 'hello' i = vowels.intersection(set(word)) #{'o', 'e'}
元祖
特性:不可变
优势:提供性能,避免不必要的开销
创建规则:特例
只有一个对象的元祖,创建时需要在末尾加上,
t = ('python') print(type(t)) #<class 'str'> print(t) #python s = ('python',) print(type(s)) #<class 'tuple'> print(s) #('python',)