Some Python Tips

Posted shiina922

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Some Python Tips相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Some Python Tips

Some tips about python

some_dict.items()是Python中的迭代器吗?

在访问对象时运行 python 命令

Some tips about argument in python

Python 中有 3 个不可思议的返回功能