Some Python Tips
2020-12-13 05:45
标签:fas lis contain cno mil gen order rman cti This is inefficient because a new string gets created upon each pass. Use a list and join it together: Similarly avoid the + operator on strings: Lists are slightly faster than sets when you just want to iterate over the values. Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though. It turns out tuples perform in almost exactly the same way as lists, except for their immutability. [1] Intermediate Python — Python Tips 0.1 documentation. https://book.pythontips.com/en/latest/ Some Python Tips 标签:fas lis contain cno mil gen order rman cti 原文地址:https://www.cnblogs.com/shiina922/p/11147883.htmlStrings
msg = 'line1\n'
msg += 'line2\n'
msg += 'line3\n'
msg = ['line1', 'line2', 'line3']
'\n'.join(msg)
# slow
msg = 'hello ' + my_var + ' world'
# faster
msg = 'hello %s world' % my_var
# or better:
msg = 'hello {} world'.format(my_var)
Sets vs Lists
Generators - Memory Saving Techniques
(f(n) for n in range(m))
instead of [f(n) for n in range(m)]
.# Generate Fibonacci series
def fab(max):
n, a, b = 0, 0, 1
while n
Some Builtin Functions
defaultdict
, OrderedDict
, counter
, deque
, namedtuple
.References
[2] performance - Python Sets vs Lists - Stack Overflow. https://stackoverflow.com/questions/2831212/python-sets-vs-lists
[3] PyBites – 5 tips to speed up your Python code. https://pybit.es/faster-python.html
[4] PythonSpeed/PerformanceTips - Python Wiki. https://wiki.python.org/moin/PythonSpeed/PerformanceTips
[5] Python yield 使用浅析 | 菜鸟教程. https://www.runoob.com/w3cnote/python-yield-used-analysis.html
[6] 生成器 - 廖雪峰的官方网站. https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128