**1. 将两个字典合并为一个字典** - update ```bash In [1]: d1 = {'a':1, 'b':2} In [2]: d2 = {'c':3, 'd':4} In [3]: d1.update(d2) In [4]: d1 Out[4]: {'a': 1, 'b': 2, 'c': 3, 'd': 4} ``` - ** 解包 ```bash In [1]: d1 = {'a':1, 'b':2} In [2]: d2 = {'c':3, 'd':4} In [3]: dict(**d1, **d2) Out[3]: {'a': 1, 'b': 2, 'c': 3, 'd': 4} ``` **2. 去重** - 列表元素去重 ```bash In [1]: lst = [5, 2, 2, 1] In [2]: set(lst) Out[2]: {1, 2, 5} ``` - 列表元素去重且保持原来的顺序 ```bash a = [5, 5, 6, 2, 2, 1, 4, 4] b = [] for x in a: if x not in b: b.append(x) print(b) # [5, 6, 2, 1, 4] ``` **3. 找出两列表中不同的元素** ```bash a = [1,2,3,4,5,6] b = [1,2,3,5] # 列表解析式 c = [x for x in a if x not in b] # [4, 6] # 转成元组,使用差集 d = set(a) - set(b) # {4, 6} ``` **4. Counter计数对象:dict类的子类** ```bash >>> from collections import Counter >>> a = Counter('hello world') >>> a Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) >>> a.most_common(2) [('l', 3), ('o', 2)] >>> a.items() dict_items([('h', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]) ``` **5. 格式化打印** ```bash >>> data = {'name':'tom', 'age':18, 'gender':'male', 'other':[{'hobbies':'playing games','fruits':'apple'},{'name':'jerry', 'age':'18', 'relationship':'friends'}]} >>> import json print(json.dumps(data, indent=2)) >>> print(json.dumps(data, indent=2)) { "name": "tom", "age": 18, "gender": "male", "other": [ { "hobbies": "playing games", "fruits": "apple" }, { "name": "jerry", "age": "18", "relationship": "friends" } ] } >>> from pprint import pprint >>> pprint(data) {'age': 18, 'gender': 'male', 'name': 'tom', 'other': [{'fruits': 'apple', 'hobbies': 'playing games'}, {'age': '18', 'name': 'jerry', 'relationship': 'friends'}]} ``` **6. 元素组合方式** ```bash >>> from itertools import combinations >>> lst = ['a', 'b', 'c', 'd'] >>> for item in combinations(lst, 2): ... print(item) ... ('a', 'b') ('a', 'c') ('a', 'd') ('b', 'c') ('b', 'd') ('c', 'd') ``` 最后修改:2019 年 03 月 19 日 09 : 08 AM © 著作权归作者所有