作者:George Seif
英文原文:https://medium.com/@george.seif94/15-python-tips-and-tricks-so-you-dont-have-to-look-them-up-on-stack-overflow-90cec02705ae
x, y = 1, 2print(x, y)x, y = y, xprint(x, y)
sentence_list = ['my', 'name', 'is', 'George']sentence_string = ' '.join(sentence_list)print(sentence_string)
3. 將字符串拆分為子字符串列表sentence_string = 'my name is George'sentence_string.split()print(sentence_string)
[0]*1000 # List of 1000 zeros [8.2]*1000 # List of 1000 8.2's
5. 字典合并x = {'a': 1, 'b': 2}y = {'b': 3, 'c': 4}z = {**x, **y}
name = 'George'name[::-1]
7. 從函數(shù)返回多個(gè)值def get_a_string(): a = 'George' b = 'is' c = 'cool' return a, b, csentence = get_a_string()(a, b, c) = sentence
a = [1, 2, 3]b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2
9. 遍歷字典m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value))
m = ['a', 'b', 'c', 'd']for index, value in enumerate(m): print('{0}: {1}'.format(index, value))
11. 初始化空容器a_list = list()a_dict = dict()a_map = map()a_set = set()
name = ' George 'name_2 = 'George///'name.strip() # prints 'George'name_2.strip('/') # prints 'George'
13. 列表中出現(xiàn)最多的元素test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]print(max(set(test), key = test.count))
import sysx = 1print(sys.getsizeof(x))
15. 將 dict 轉(zhuǎn)換為 XMLfrom xml.etree.ElementTree import Elementdef dict_to_xml(tag, d): ''' Turn a simple dict of key/value pairs into XML ''' elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) elem.append(child) return elem