1. list使用sort排序
Python2中的list既可以是字符串和数字,然后使用sort排序,排序的时候使用Ascall码。
list1 = [‘a‘,‘b‘,123] list1.sort() print list1 # 运行结果:[123, ‘a‘, ‘b‘]
Python3中的list必须是纯数字才可以排序。
list1 = [‘a‘,‘b‘,123] list1.sort() # 运行结果: Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/20180119/index.py", line 12, in <module> list1.sort() TypeError: ‘<‘ not supported between instances of ‘int‘ and ‘str‘
2. 应熟练使用dict.setdefault()函数
result = {} data = [{'domain': "baidu.com", "kw": "张三"},{'domain': "baidu.com", "kw": "李四"}, {'domain': "baidu2.com", "kw": "王五"}, {'domain': "jd.com", "kw": "田陆"}] for it in data: result.setdefault(it.get("domain"), []).append(it.get("kw")) print data # 运行结果 [{'domain': 'baidu.com', 'kw': 'xe5xbcxa0xe4xb8x89'}, {'domain': 'baidu.com', 'kw': 'xe6x9dx8exe5x9bx9b'}, {'domain': 'baidu2.com', 'kw': 'xe7x8ex8bxe4xbax94'}, {'domain': 'jd.com', 'kw': 'xe7x94xb0xe9x99x86'}]