Python basis Supplements

1. list sorted using the sort

Python2 The list can be both strings and numbers, then use Ascall code sort, the sort time.

= List1 [ 'A', 'B', 123 ] 
list1.sort () 
Print List1
 # Run Results: [123, 'a', 'b']

Python3 in the list must be pure numbers can only be sorted.

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. should be familiar with dict.setdefault () function

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': '\xe5\xbc\xa0\xe4\xb8\x89'}, {'domain': 'baidu.com', 'kw': '\xe6\x9d\x8e\xe5\x9b\x9b'}, {'domain': 'baidu2.com', 'kw': '\xe7\x8e\x8b\xe4\xba\x94'}, {'domain': 'jd.com', 'kw': '\xe7\x94\xb0\xe9\x99\x86'}]

Guess you like

Origin www.cnblogs.com/liangsha0/p/12158079.html