True True color is {'yellow', 'green', 'blue'} copy color is {'yellow', 'green', 'blue'} remove greeen and add pink to color_copy color is {'yellow', 'green', 'blue'} copy color is {'yellow', 'pink', 'blue'} {'yellow', 'blue'} {'yellow', 'green', 'pink', 'blue'}
deftotal(a=5, *numbers, **phonebook): print('a', a) #遍历元组中的所有项目 for single_item in numbers: print('single_item', single_item)
#遍历字典中的所有项目 for first_part, second_part in phonebook.items(): print(first_part,second_part) print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
Output
1 2 3 4 5 6 7 8
a 10 single_item 1 single_item 2 single_item 3 Inge 1560 John 2231 Jack 1123 None
DocStrings
Python 有一个甚是优美的功能称作文档字符串(Documentation Strings),在称呼它时通常会使用另一个短一些的名docstrings。DocStrings 是一款你应当使用的重要工具,它能够帮助你更好地记录程序并让其更加易于理解 Example
1 2 3 4 5 6 7 8 9 10 11 12 13
defprint(self, *args, sep=' ', end='\n', file=None):# known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. """ pass print(print.__doc__)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
enumerate()函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中 语法
>>> classa(): ... pass ... >>> classb(a): ... pass ... >>> issubclass(a, b) False >>> issubclass(b, a) True >>> issubclass(b, b) True >>> issubclass(b, object) True >>>
对不确定是否存在的字典的键进行赋值
语法
setdefault(key[, default])
Example
1 2 3 4 5
>>> a = {} >>> a.setdefault('b', 1) 1 >>> a {'b': 1}
本来是这样写的代码
1 2 3 4 5 6 7 8 9 10 11
>>> defcount(datas): ... result = {} ... for data in datas: ... if data in result: ... result[data] += 1 ... else: ... result[data] = 1 ... return result ... >>> count(data) {'a': 2, 'b': 2, 'c': 3, 'd': 1}
现在只要这样写就行了
1 2 3 4 5 6 7 8 9
>>> defcount(datas): ... result = {} ... for data in datas: ... result.setdefault(data, 0) ... result[data] += 1 ... return result ... >>> count(data) {'a': 2, 'b': 2, 'c': 3, 'd': 1}
@retry defsave_to_database(arg): print('Write to a database or make a network call or etc.') print('This will be automatically retried if exception is thrown.') global counter counter += 1 # 这将在第一次调用时抛出异常 # 在第二次运行时将正常工作(也就是重试) if counter < 2: raise ValueError(arg)
if __name__ == '__main__': save_to_database('Some bad value')