码迷,mamicode.com
首页 > 编程语言 > 详细

Some Python Tips

时间:2019-07-07 21:37:15      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:fas   lis   contain   cno   mil   gen   order   rman   cti   

Strings

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)

Sets vs Lists

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.

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 < max: 
        yield b  # Use `yield`
        a, b = b, a + b 
        n = n + 1
 
for n in fab(5): 
    print(n)

Some Builtin Functions

defaultdict, OrderedDict, counter, deque, namedtuple.

References

[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

Some Python Tips

标签:fas   lis   contain   cno   mil   gen   order   rman   cti   

原文地址:https://www.cnblogs.com/shiina922/p/11147883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!