标签:fas lis contain cno mil gen order rman cti
msg = 'line1\n'
msg += 'line2\n'
msg += 'line3\n'
This is inefficient because a new string gets created upon each pass. Use a list and join it together:
msg = ['line1', 'line2', 'line3']
'\n'.join(msg)
Similarly avoid the + operator on strings:
# slow
msg = 'hello ' + my_var + ' world'
# faster
msg = 'hello %s world' % my_var
# or better:
msg = 'hello {} world'.format(my_var)
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.
(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 < max:
yield b # Use `yield`
a, b = b, a + b
n = n + 1
for n in fab(5):
print(n)
defaultdict
, OrderedDict
, counter
, deque
, namedtuple
.
[1] Intermediate Python — Python Tips 0.1 documentation. https://book.pythontips.com/en/latest/
[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
标签:fas lis contain cno mil gen order rman cti
原文地址:https://www.cnblogs.com/shiina922/p/11147883.html