Python is said to come with a battery, so it has a lot of built-in functions and standard libraries. On the other hand, I think there are many functions that are too rich to see the light of day.
The original motivation for writing this is the print function. It should be evaluated more.
Let's read the following once: Python Tutorial as well as Standard Library Mini Tour Standard Library Mini Tour Part 2
print The child itself is very famous, but the arguments may be shaders.
In Python2, the print statement changed from Python3 to the print function. I was wondering what it means other than breaking backward compatibility, but if you look closely, it has evolved into a very convenient function. T:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
- sep -
You can set the delimiter, similar to join
:
print('a', 'b', 'c', 'd', sep='_')
# '_'.join(['a', 'b', 'c', 'd'])
>>> a_b_c_d
- end -
You can specify what to put at the end of the output. The default is of course \ n
:
print('Hello ', end=''); print('World')
>>> Hello World
- file -
This is the most moving point. ** File output is possible with print
**:
f = open('output.txt', 'w')
print('Hello World', file=f)
When you google, it is often introduced how to use write ()
or writeline ()
, but from now on you can use print
!
- flush -
You can flush the buffer. For example, writing a file is not when you run print (..., file = f)
, but when the buffer is full. Probably for performance, If you want to peek at the written file during execution, you want it to be output immediately. In such a case, set flush
to True.
-Matching technique- For example, suppose you want to print the number of loops to the console when doing something:
for i in range(100):
print('rep = {0}'.format{i})
#Something like the following...
>>> rep = 0
rep = 1
rep = 2
rep = 3
...
But this is a waste of console space with the output lined up vertically. ** Let's overwrite the output: **
for i in range(100):
print('rep = {0}'.format{i}, '\r', end='', flush=True)
#Something like the following...
\ r
is an escape sequence that returns the cursor position to the beginning of the line. This overwrites the output and fits on one line. It's convenient.
pprint
** pretty-print, abbreviated pprint
**. As the name implies, it makes the output cute. Probably the definition of "cute" here is "output that does not fit the width of the console is divided into multiple lines. It seems to be "output state":
from pprint import pprint
pprint('There should be one-- and preferably only one --obvious way to do it.'.split())
>>> ['There',
'should',
'be',
'one--',
'and',
'preferably',
'only',
'one',
'--obvious',
'way',
'to',
'do',
'it.']
I don't know if it's cute, but it can be useful. It doesn't feel as versatile as the print
function.
shelve
It is common to save the numerical calculation result in a txt, csv file, etc., but if you try to read this again with Python, it will be a string type, so you have to follow the procedure of casting it to int / float ... No. ** shelve
can save and expand objects in Python as is: **
import shelve
zen_string = 'There should be one-- and preferably only one --obvious way to do it.'
zen_list = zen_string.split()
#Create a new Helve object
obj = shelve.open('./test')
#Substitution like dict type
obj['string'], obj['list'] = zen_string, zen_list
#Save(close)
obj.close()
#Deployment
obj_restore = shelve.open('./test')
print(list(obj_restore.keys()))
>>> ['string', 'list']
print(obj_restore['string'])
>>> 'There should be one-- and preferably only one --obvious way to do it.'
This should be useful if you live in Python! But is it versatile because it cannot be accessed from other languages and tools?
collections.deque
list is a convenient container, but adding / removing elements other than the end is very inefficient. collections.deque
can execute append and pop at both ends at high speed:
import numpy as np
from collections import deque
a = np.linspace(0, 1, 100000)
b = deque(a)
# IPython
%timeit -n5 a.pop(0)
>>> 5 loops, best of 3: 35.6 µs per loop
%timeit -n5 b.popleft()
>>> 5 loops, best of 3: 147 ns per loop
** 200 times or more ** </ font> is fast. If you use Python with Procon, I think it is essential.
The convenience of IPython has been talked about in many places: How to use IPython
If you add ?
After the command, you can refer to the help, you can use the shell command as it is, and it is convenient such as magic command.
IPython.embed Stop in the middle of running the code and enter IPython.
from IPython import embed
tmp = []
for i in range(100):
tmp.append(i)
if i == 50:
# i ==Enter with IPython at 50
embed()
# IPython
In [1]: tmp
Out[1]:
[0,
1,
2,
...
50]
# exit()Or Ctrl-When I exit IPython with D or something, execution resumes
For example, if a strange error occurs, you can check the contents of the object by inserting ʻembed ()` just before that. For those who want to graduate from print debugging but the debugger has a high threshold ... I'd love to.
I've listed some of the things I use a lot that aren't very well known. If there's something good, I'll add it. If there's something good, please let me know.
Recommended Posts